﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Linq;
using System.Xml;
using System.Data.SqlClient;

using CE.User;
using CE.Global;
using CE.Database;
using CE.CarInsurance;
using CE.Mail;

public partial class carinsurance_offline_ViewCINoMatchFound : System.Web.UI.Page
{
    private DateTime dateTimeNow = CE.Global.General.GetUTCDateTime();

    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] == null)
        {
            Response.Redirect("~/SiteUserSecureLogin.aspx");
        }

        if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "201")
        {
            Response.Redirect("~/carinsurance/PendingApplication.aspx");
        }

        ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
        scriptManager.RegisterPostBackControl(this.btnExcelPremiumDownload);

        if (!IsPostBack)
        {
            CE.User.AccountStatusDB _accountStatusDB = new CE.User.AccountStatusDB();
            int _pwdStatus = _accountStatusDB.GetLastPasswordChagedStatus(Convert.ToInt64(Session[CE.Global.General.UserId].ToString()));
            if (_pwdStatus == 1)
            {
                Response.Redirect("~/User/ChangePassword.aspx");
            }

            txtGG.Text = "PROVIDER";
            //For monthly Installment -- start
            ddlGGDiscount.Items.Clear();
            ddlGGDiscount.Items.Add(new ListItem(0 + " %", "0"));
            ddlNoofInstallments.Items.Clear();
            ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
            lblCreditCardAllowed.Text = "1. " + Resources.CarInsurance.BankK;
            lblCreditCardAllowed.ForeColor = System.Drawing.Color.Green;

            lblInterest.Text = Resources.CarInsurance.InterestFree;
            //For monthly Installment -- End

            if (Request.Params["calltype"] != null)
            {
                lblCallType.Text = Request.Params["calltype"].ToString();
                ShowCallTypeDesc();
            }
            else
            {
                Response.Redirect("~/SiteUserHome.aspx");
            }

            if (Request.QueryString["tabid"] != null)
            {
                hidLastTab.Value = Request.QueryString["tabid"].ToString();
            }

            if (Request.Params["leadid"] != null && Request.Params["calltype"] != null
                && Request.Params["carid"] != null && Request.Params["custid"] != null)
            {
                Int64 _leadId = 0;
                Int16 _callType = 0;
                Int64 _carId = 0;
                Int64 _custId = 0;

                if (Int64.TryParse(Request.Params["leadid"].ToString(), out _leadId)
                    && Int16.TryParse(Request.Params["calltype"].ToString(), out _callType)
                    && Int64.TryParse(Request.Params["carid"].ToString(), out _carId)
                    && Int64.TryParse(Request.Params["custid"].ToString(), out _custId))
                {
                    //Call Type = 102 and 103 can be CarID and CustomerID ZERO
                    if (_carId == 0 && _custId == 0)
                    {
                        string _strCallMeId = "0";

                        if (Request.Params["callmeid"] != null)
                        {
                            _strCallMeId = Request.Params["callmeid"].ToString();
                        }

                        if (_callType == 103)
                        {
                            Response.Redirect("callme-newlead-quotes.aspx?leadid=" + _leadId.ToString() + "&callmeid=" + _strCallMeId + "&calltype=" + _callType.ToString() + "&carid=0" + "&custid=0");
                        }
                        else
                        {
                            Response.Redirect("~/carinsurance/ViewCICustomerCallNewSearch.aspx?leadid=" + _leadId.ToString() + "&callmeid=" + _strCallMeId + "&calltype=" + _callType.ToString());
                        }
                    }
                    else if (_carId == 0 && _custId != 0 && _callType == 100)
                    {
                        //28March2014 Promotion
                        //if (!ShowScreen())
                        //{
                        if (_leadId != 0)
                        {
                            Response.Redirect("~/carinsurance/offline/callme-newlead-quotes.aspx?leadid=" + _leadId.ToString() + "&callmeid=0&calltype=" + _callType.ToString() + "&carid=0&custid=" + _custId.ToString());
                        }

                        //if ((dateTimeNow.Hour >= 9 && dateTimeNow.Hour <= 10)
                        //    || (dateTimeNow.Hour >= 13 && dateTimeNow.Hour <= 14)
                        //    || (dateTimeNow.Hour >= 17))
                        //{
                        //    lblCallSessionName.Text += "<br/><br/>" + "Sorry, please try again later.<br/> You don't have any more follow up or call back.";
                        //}
                        //else
                        //{
                        //    lblCallSessionName.Text += "<br/><br/>" + Resources.General.NORECORDFOUND;
                        //    lblCallSessionName.Text += "<br/><br/>INVALID. NOT FOUND! CHECK CX IT TEAM.";
                        //}
                        //ResetAll();
                        //}
                    }
                    else if (_carId == 0 && _custId != 0 && _callType == 101)
                    {
                        //28March2014 Promotion
                        //if (!ShowScreen())
                        //{
                        if (_leadId != 0)
                        {
                            Response.Redirect("~/carinsurance/offline/callme-newlead-quotes.aspx?leadid=" + _leadId.ToString() + "&callmeid=0&calltype=" + _callType.ToString() + "&carid=0&custid=" + _custId.ToString());
                        }
                    }
                    else if (!ShowScreen(_leadId, _callType, _carId, _custId))
                    {
                        lblCallSessionName.Text = Resources.General.NORECORDFOUND;
                        ResetAll();
                    }
                    if (_custId > 0)
                    {
                        txtUserTypeId.Text = GetUserTypeId(_custId).ToString();
                    }
                }
                else
                {
                    Response.Redirect("~/SiteUserHome.aspx");
                }
            }
            else if (!ShowScreen())
            {
                if ((dateTimeNow.Hour >= 9 && dateTimeNow.Hour <= 10)
                    || (dateTimeNow.Hour >= 13 && dateTimeNow.Hour <= 14)
                    || (dateTimeNow.Hour >= 17))
                {
                    lblCallSessionName.Text += "<br/><br/>" + "Sorry, please try again later.<br/> You don't have any more follow up or call back.";
                }
                else
                {
                    lblCallSessionName.Text += "<br/><br/>" + Resources.General.NORECORDFOUND;
                    lblCallSessionName.Text += "<br/><br/>INVALID. NOT FOUND! CHECK CX IT TEAM.";
                }
                ResetAll();
            }

            // Lead AH
            GetCustomerUserId();

            //Added on 06 Sep 2013 - Start
            Int64 _IntCarId = 0;
            Int64 _IntAgentId = 0;
            if (!Int64.TryParse(txtCarId.Text, out _IntCarId))
            {
                _IntCarId = 0;
            }
            if (!Int64.TryParse(Session[General.UserId].ToString(), out _IntAgentId))
            {
                _IntAgentId = 0;
            }
            if (_IntCarId > 0 && _IntAgentId > 0)
            {
                UpdateUsedLeadStatus(_IntCarId, _IntAgentId);
            }
            //Added on 06 Sep 2013 - End
            LoadNoofPaylist();
            //Added 11 Mar 2013 -- Start
            LoadgentbyAdmin();
            if (ddlAgentbyAdmin.Items.Count > 1)
            {
                if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "100")
                {
                    if (Session[General.UserId] != null)
                    {
                        ddlAgentbyAdmin.Text = Session[General.UserId].ToString();
                        ddlAgentbyAdmin.Enabled = false;
                    }
                    else
                    {
                        ddlAgentbyAdmin.Enabled = true;
                    }
                }
                else
                {
                    ddlAgentbyAdmin.Enabled = true;
                }
            }
            //Added 11 Mar 2013 -- End
        }
        else
        {
            //lblPremiumError.Text = "";
            //lblPremiumMessage.Text = "";

            lblSendOrderConfirmationMessage.Text = "";
            lblMessageKawna.Text = "";
            lblCallStatusMessage.Text = "";

            if (chkExtComDate.Checked)
                ddlExtComDate.Style.Add("visibility", "visible");
            else
                ddlExtComDate.Style.Add("visibility", "hidden");

            // ************** Tesco & World Cup ****************
            if (chkGetTesco.Checked)
                //chkChangePremium.Enabled = false;
                chkChangePremium.InputAttributes.Add("disabled", "true");
            else
                //chkChangePremium.Enabled = true;
                chkChangePremium.InputAttributes.Remove("disabled");

            if (hidFinalAnnualPremium.Value != "")
            {
                txtFinalAnnualPremium.Text = hidFinalAnnualPremium.Value;
                hidFinalAnnualPremium.Value = "";
            }
            //**************************************************

            if (ddlNInsuranceType.SelectedValue == "10" || ddlNInsuranceType.SelectedValue == "11")
            {
                trClass11.Style.Remove("display");
                trClass12.Style.Remove("display");
            }
            else
            {
                trClass11.Style.Add("display", "none");
                trClass12.Style.Add("display", "none");
            }
        }
    }

    private DateTime GetCallBackDateLimit(int limitDate)
    {
        DateTime dateTimeCallback = new DateTime();
        try
        {
            MyDatabase _db = new MyDatabase();
            object rtnDate = _db.ExecuteScalarSqlStatement("SELECT dbo.fn_countDateNoHolliday(dbo.fn_getUTCDateTime()," + limitDate.ToString() + ",1) CallBackDate");
            if (rtnDate != null)
            {
                dateTimeCallback = Convert.ToDateTime(rtnDate);
            }
            else
            {
                dateTimeCallback = dateTimeNow.AddDays(21);
            }
        }
        catch (Exception)
        {
        }
        return dateTimeCallback;
    }

    public Int64 GetUserTypeId(Int64 CustomerId)
    {
        Int64 _result = 400;
        try
        {
            MyDatabase _db = new MyDatabase();
            string _strSelect = "SELECT UsrTypeId FROM tblCEUser WHERE CEID = " + CustomerId.ToString();

            DataTable _dtUsrTypeId = new DataTable("tblUsrTypeId");

            _dtUsrTypeId = _db.GetDataTable(_strSelect);

            if (_dtUsrTypeId != null && _dtUsrTypeId.Rows.Count > 0)
            {
                if (_dtUsrTypeId.Rows[0]["UsrTypeId"] != DBNull.Value)
                {
                    _result = Convert.ToInt64(_dtUsrTypeId.Rows[0]["UsrTypeId"].ToString());
                }
            }
        }
        catch (Exception Ex)
        {
        }
        return _result;
    }

    private void LoadControlData()
    {
        ddlExtComDate.Style.Add("visibility", "hidden");

        DateTime time = dateTimeNow;
        lblStartDateTime.Text = time.ToString("dd/MMM/yyyy hh:mm:ss tt"); //Don't use HTML tag inside text
        lblStartDayName.Text = "<b style='color:red;'>" + time.ToString("dddd") + " </b>";
        hplReRunQuote.Attributes.Add("onclick", "javascript:return confirm('" + Resources.General.ConfirmReRunQuoteMessage + "');");
        hplNewQuote.Attributes.Add("onclick", "javascript:return confirm('" + Resources.General.ConfirmRunNewQuoteMessage + "');");

        LoadBrokerProvider();
        LoadBrokerCoverType();

        DateTime _dtNow = dateTimeNow;

        TimeSpan dateDiff = General.GetUTCDateTimeToday().AddMonths(6) - General.GetUTCDateTimeToday(); //DateTime.Today.AddMonths(4) - DateTime.Today;

        for (int d = 0; d <= dateDiff.TotalDays; d++)
        {
            ddlEditCoverCommencementDate.Items.Add(new ListItem(_dtNow.ToString("dd/MMM/yyyy"), _dtNow.ToString("dd/MMM/yyyy")));
            _dtNow = _dtNow.AddDays(1);
        }

        ddlEditCoverCommencementDate.Text = dateTimeNow.ToString("dd/MMM/yyyy");
        lblEditCoverCommencementDate.Text = ddlEditCoverCommencementDate.Text;

        lblResetUrl.Text = Request.Url.ToString();
        ResetAll();
        txtAgentId.Text = Session[General.UserId].ToString();
        LoadAgentList();
        
        txtTargetDate.Text = dateTimeNow.ToString("dd-MMM-yyyy");
        cexTargetDate.StartDate = dateTimeNow;
        cexTargetDate.EndDate = GetCallBackDateLimit(15); //dateTimeNow.AddDays(21);
        ddlCIMainCallStatus.Items.Clear();
        ddlCICallStatus.Items.Clear();
        rdoCallFinish.Checked = true;
        rdoCallFinish_CheckedChanged(null, null);

        if (ddlCIMainCallStatus.Items.Count > 0)
        {
            ddlCIMainCallStatus.SelectedIndex = 0;
            ddlCIMainCallStatus_SelectedIndexChanged(null, null);
        }
    }

    #region ExtComDateRenew

    private void LoadExtComDate()
    {
        if (ddlExtComDate.Items.Count <= 0)
        {
            DateTime _dtNowExtFrom = new DateTime(General.GetUTCDateTimeToday().Year + 1, 1, 1);
            DateTime _dtNowExtTo = new DateTime(General.GetUTCDateTimeToday().Year + 1, 12, 31);
            TimeSpan dateDiffExt = _dtNowExtTo - _dtNowExtFrom;
            for (int d = 0; d <= dateDiffExt.TotalDays; d++)
            {
                ddlExtComDate.Items.Add(new ListItem(_dtNowExtFrom.ToString("dd/MMM/yyyy"), _dtNowExtFrom.ToString("yyyy-MM-dd")));
                _dtNowExtFrom = _dtNowExtFrom.AddDays(1);
            }
            ddlExtComDate.Items.Insert(0, new ListItem("", ""));
        }
    }

    #endregion

    #region ShowCarPlateNumber
    //private void ShowCarPlateNumber(Int64 CECarID, Int64 CustomerID)
    //{
    //    BrokerPremiumDB _db = new BrokerPremiumDB();
    //    string _carplateNumber = _db.GetCarPlate(CECarID, CustomerID);
    //    if (_carplateNumber != string.Empty)
    //    {
    //        txtEditLicensePlate.Text = _carplateNumber;
    //        lblEditLicensePlate.Text = _carplateNumber;
    //    }
    //}
    #endregion

    private void ShowLastQuotationSendDate(Int64 CECarID, Int64 CustomerID)
    {
        BrokerPremiumDB _db = new BrokerPremiumDB();
        string _lastSendStatus = _db.GetLastQuotationSendDate(CECarID, CustomerID, 1);
        if (_lastSendStatus != string.Empty)
        {
            string[] strLastSendValues = _lastSendStatus.Split(',');
            lblSendQuotationMessage.Text = Resources.General.QuotationSent + " > " + strLastSendValues[0];
            txtConfirmEmail.Text = strLastSendValues[0];

            lblSendQuotationMessage.Text += " > " + Convert.ToDateTime(strLastSendValues[1]).ToString("dd/MMM/yyyy hh:mm tt");

        }
    }

    private void ShowLastOrderConfirmationSendDate(Int64 CECarID, Int64 CustomerID)
    {
        BrokerPremiumDB _db = new BrokerPremiumDB();
        string _lastSendStatus = _db.GetLastQuotationSendDate(CECarID, CustomerID, 3);
        if (_lastSendStatus != string.Empty)
        {
            string[] strLastSendValues = _lastSendStatus.Split(',');
            lblSendOrderConfirmationMessage.Text = "<br/>" + Resources.General.OrderConfirmationSent + " > " + strLastSendValues[0];
            txtConfirmEmail.Text = strLastSendValues[0];

            lblSendOrderConfirmationMessage.Text += " > " + Convert.ToDateTime(strLastSendValues[1]).ToString("dd/MMM/yyyy hh:mm tt");

        }
    }
    
    private void ShowFirstOrderConfirmationSendDate(Int64 CECarID, Int64 CustomerID)
    {
        BrokerPremiumDB _db = new BrokerPremiumDB();
        string _lastSendStatus = _db.GetFirstQuotationSendDate(CECarID, CustomerID);
        if (_lastSendStatus != string.Empty)
        {
            string[] strLastSendValues = _lastSendStatus.Split(',');
            lblSendFirstOrderConfirmationMessage.Text = "ส่งครั้งแรก : " + Resources.General.QuotationSent + " > " + strLastSendValues[0];
            lblSendFirstOrderConfirmationMessage.Text += " > " + Convert.ToDateTime(strLastSendValues[1]).ToString("dd/MMM/yyyy hh:mm tt");
            hidFirstPdfDate.Value = strLastSendValues[1];
            //<a runat="server" id="aPdfLoad" onserverclick="btnShowFirstOrderConfirmation_Click">Open Pdf</a>
            if (strLastSendValues.Length > 2)
            {
                btnShowFirstOrderConfirmation.Visible = true;
                hidFirstPdfFile.Value = strLastSendValues[2];
            }
        }
    }

    private void CheckFirstQuote()
    {
        if (hidFirstPdfDate.Value.Trim() != "")
        {
            DateTime _dtToDate = new DateTime(dateTimeNow.Year, dateTimeNow.Month, dateTimeNow.Day);
            DateTime _sentDte = Convert.ToDateTime(hidFirstPdfDate.Value);

            if ((_dtToDate - _sentDte).TotalDays > 7)
            {
                //DateTime _tempDate = _sentDte;
                //for (int i = 0; i < 7; i++)
                //{
                //    if (_tempDate.AddDays(1).DayOfWeek == DayOfWeek.Saturday ||
                //        _tempDate.AddDays(1).DayOfWeek == DayOfWeek.Sunday)
                //    {
                //        i--;
                //    }
                //    _tempDate = _tempDate.AddDays(1);
                //}
                //if (_dtToDate > _tempDate)
                //{
                //    chkIsPromotion.Checked = false;
                //    chkIsPromotion.Enabled = false;
                //}
                chkIsPromotion.Checked = false;
                chkIsPromotion.Enabled = false;
            }
        }
    }

    protected void btnShowFirstOrderConfirmation_Click(object sender, EventArgs e)
    {
        if (grvPremiumList.Rows.Count > 0)
        {
            FileInfo file = new System.IO.FileInfo(hidFirstPdfFile.Value);
            if (!file.Exists)
            {
                ClientScript.RegisterStartupScript(btnPremiumDownload.GetType(), "DownloadPremiumAlert", "alert('No item to download!');", true);
                return;
            }
            Response.Clear();
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetNoStore();
            Response.Cache.SetExpires(DateTime.MinValue);
            Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
            Response.AddHeader("Content-Length", file.Length.ToString());
            Response.ContentType = "application/octet-stream";
            Response.WriteFile(file.FullName);
            ApplicationInstance.CompleteRequest();
            Response.End();
        }
        else
        {
            ClientScript.RegisterStartupScript(btnPremiumDownload.GetType(), "DownloadPremiumAlert", "alert('No item to download!');", true);
        }
    }

    private string GetCallDuration()
    {
        DateTime _dtStartTime = Convert.ToDateTime(lblStartDateTime.Text);
        TimeSpan _duration = dateTimeNow - _dtStartTime;
        string _strMin = _duration.Minutes.ToString();
        string _strSec = _duration.Seconds.ToString();
        txtMinute.Text = _strMin;
        txtSecond.Text = _strSec;

        if (Convert.ToInt16(_strMin) < 10)
        {
            _strMin = "0" + _strMin;
        }

        if (Convert.ToInt16(_strSec) < 10)
        {
            _strSec = "0" + _strSec;
        }

        return _strMin + " : " + _strSec;
    }

    protected void ResetAll()
    {
        txtCarId.Text = "";
        txtCarPolicyId.Text = "";
        hplReRunQuote.NavigateUrl = "";
        hplNewQuote.NavigateUrl = "";
        divLinks.Visible = false;

        lblCallStatusMessage.Text = "";
        divCallStatus.Visible = false;
        divCompletedQuoteDetails.Visible = false;
        divCustomerPolicyDetail.Visible = false;
        divCallHistory.Visible = false;

        divResultExcel.Visible = false;

        divEditDetail.Visible = false;

        divPremiumList.Visible = false;
        btnReset.Visible = false;

        ResetCallStatus();
    }

    protected void btnCustomerDetailRemark_Click(object sender, EventArgs e)
    {
        try
        {
            MyDatabase _db = new MyDatabase();
            string strUpdate = "Update tblCEContact SET OtherContact1 = @OtherContact1 Where RefCEUserID = @CustomerID";
            SortedList _paraList = new SortedList();
            _paraList.Add("@OtherContact1", Server.HtmlEncode(txtCustomerDetailRemark.Text));
            _paraList.Add("@CustomerID", txtCustomerId.Text);
            int _affRow = _db.ExecuteNonSqlStatement(strUpdate, _paraList);
            if (_affRow > 0)
            {
                lblCustomerDetailRemarkMessage.Text = "Saved at " + dateTimeNow.ToString("dd-MMM-yyyy hh:mm tt");
            }
        }
        catch (Exception Ex)
        {
            lblCustomerDetailRemarkMessage.Text = Ex.Message;
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        txtCallStatusId.Text = "0";
        txtCarId.Text = "";
        txtCustomerId.Text = "";


        lblCallStatusMessage.Text = "";
        divCallStatus.Visible = false;
        divCustomerPolicyDetail.Visible = false;
        divCXBrokerPremium.Visible = false;

        hplPremiumDownLoad.Visible = false;
        hplPremiumDownLoad.NavigateUrl = "";
    }

    protected void btnCallStatus_Click(object sender, EventArgs e)
    {
        lblCallStatusMessage.Text = "";
        //lblLastCallStatusMessage.Text = "";
        //Page.Validate("callstatus");

        if (Page.IsValid)
        {
            // *** Start Validate ***
            if (rdoCallBack.Checked)
            {
                //Over 60 Days, not check
                if (ddlCICallStatus.Text != "10")
                {
                    int _callBackCount = 0;
                    if (int.TryParse(txtCallBackCount.Text, out _callBackCount))
                    {
                        if (_callBackCount > 20)
                        {
                            lblCallStatusMessage.Text = Resources.General.Callback + " (" + Resources.General.CallBackLimitMessage + ") " + Resources.General.FAIL + " " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm:ss tt");
                            return;
                        }
                    }
                }
            }

            //Over 60 Days, check
            if (ddlCICallStatus.Text == "10")
            {
                DateTime _dtCoverCommDate = dateTimeNow;
                if (DateTime.TryParse(lblEditCoverCommencementDate.Text, out _dtCoverCommDate))
                {
                    DateTime _sdtNow = Convert.ToDateTime(txtCallBackDateTime.Text);
                    DateTime _dtNow = new DateTime(_sdtNow.Year, _sdtNow.Month, _sdtNow.Day);

                    if (DateTime.Compare(_dtCoverCommDate, _dtNow) <= 0)
                    {
                        lblCallStatusMessage.Text = Resources.General.CommencementCheck;
                        ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.CommencementCheck + "');", true);
                        return;
                    }
                    else
                    {
                        lblEditCoverCommencementDateCaption.ForeColor = System.Drawing.Color.Gray;
                        lblEditCoverCommencementDateMessage.Text = string.Empty;
                    }
                }
                else
                {
                    lblCallStatusMessage.Text = Resources.General.CommencementCheck;
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.CommencementCheck + "');", true);
                    return;
                }
            }
            // *** End Validate ***

            if (txtCarId.Text.Length > 0 && txtCustomerId.Text.Length > 0)
            {
                //*** Promotion 
                //28March2014
                if (rdoCallFinish.Checked || rdoCallNotBuy.Checked)
                {
                    if (hidPromotionId.Value != "")
                    {
                        PromotionGGDB objPro = new PromotionGGDB();
                        objPro.UpdateAgent(Convert.ToInt64(hidPromotionId.Value), Convert.ToInt64(txtCustomerId.Text));
                    }
                }

                CallStatus callstatus = new CallStatus();
                CallStatusDB callstatusdb = new CallStatusDB();

                callstatus = callstatusdb.GetCallStatus(Convert.ToInt64(lblAgentLeadID.Text), Convert.ToInt32(lblCallType.Text));

                if (callstatus == null)
                {
                    callstatus = new CallStatus();
                }

                callstatus.CarId = Convert.ToInt64(txtCarId.Text);
                if (Session[CE.Global.General.CarResultId] != null)
                {
                    callstatus.CarResultId = Convert.ToInt64(Session[CE.Global.General.CarResultId].ToString());
                }
                callstatus.CustomerId = Convert.ToInt64(txtCustomerId.Text);
                callstatus.AgentId = Convert.ToInt64(txtAgentId.Text);

                callstatus.AgentLeadId = Convert.ToInt64(lblAgentLeadID.Text);

                if (rdoCallFinish.Checked || rdoCallNotBuy.Checked)
                {
                    callstatus.CallFinishType = 1;
                }
                else if (rdoCallBack.Checked)
                {
                    callstatus.CallBackDateTime = Convert.ToDateTime(txtCallBackDateTime.Text);
                    callstatus.CallBackAgentID = Convert.ToInt64(ddlCBAgentList.Text);
                    callstatus.CallFinishType = 2;
                }

                //27Feb2014
                //if (ddlCIMainCallStatus.Text == "7" && ddlCICallStatus.Text == "10")
                //{
                //    callstatus.CallBackDateTime = Convert.ToDateTime(txtCallBackDateTime.Text);
                //    callstatus.CallBackAgentID = Convert.ToInt64(Session[General.UserId].ToString());
                //}

                callstatus.MainCallStatusTypeID = Convert.ToInt32(ddlCIMainCallStatus.Text);
                callstatus.CallStatusTypeID = Convert.ToInt32(ddlCICallStatus.Text);
                callstatus.CallTypeId = Convert.ToInt32(lblCallType.Text);
                callstatus.StartDateTime = Convert.ToDateTime(lblStartDateTime.Text);
                callstatus.Remark = Server.HtmlEncode(txtCallStatus.Text);
                callstatus.CXCRMId = callstatusdb.Insert(callstatus);

                if (callstatus.CXCRMId > 0)
                {
                    //Invalid/Wrong Number | Car sold  | Phone number not actual owner
                    //Update tblCEUser.IsReject
                    if (ddlCICallStatus.Text == "2" || ddlCICallStatus.Text == "38")
                    {
                        if (lblEmailAddress.Text.Trim() != "") UnSubscribeUserList(lblEmailAddress.Text.Trim());
                    }

                    if (txtCXCRMId.Text.Length > 0 && txtCXCRMId.Text != "0")
                    {
                        lblCallStatusMessage.Text = Resources.General.UPDATE + " " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm:ss tt");
                    }
                    else
                    {
                        txtCXCRMId.Text = callstatus.CXCRMId.ToString();
                        lblCallStatusMessage.Text = Resources.General.SUCCESS + " " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm:ss tt");
                    }

                    lblCallDurationTimer.Visible = false;

                    lblCallStatusMessage.Text += ", " + Resources.General.CallDuration + ": " + GetCallDuration();
                    btnNext.Visible = true;
                    btnCallStatus.Enabled = false;
                }
                else
                {
                    lblCallStatusMessage.Text = Resources.General.FAIL + " " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm:ss tt");
                }
                callstatus = null;
                callstatusdb = null;

                // Yui@18/11/2014 ไม่เปลี่ยนหน้าแล้ว
                //if (Session[General.IsRenewalAgent].ToString() == "1")
                //{
                //    Response.Redirect("~/carinsurance/RenewalQuotes.aspx");
                //}
            }
            else
            {
                lblCallStatusMessage.Text = Resources.General.FAIL;
            }
        }
    }

    #region SaveReject_InvalidNumber

    private void UnSubscribeUserList(string EmailList)
    {
        try
        {
            MyDatabase _db = new MyDatabase();
            string _spName = "[sprocCXRejectEmailInsertUpdateSelectedItemList]";

            SortedList _sPara = new SortedList();

            #region Parameter
            _sPara.Add("@EmailList", EmailList);
            _sPara.Add("@EDM", 2);
            _sPara.Add("@EDMType", "2.EDM - Unsubscribe Update");
            #endregion

            DataTable _dt = _db.GetDataTableBySP(_spName, _sPara);
        }
        catch (Exception)
        {
        }
    }

    #endregion

    protected void btnSubmitPremium_Click(object sender, EventArgs e)
    {
        if (Convert.ToInt32(lblCarMoreDetailID.Text) > 0)
        {
            btnSubmitPremium.Enabled = false;
            btnNewPremium.Enabled = false;
            btnEditSubmit.Enabled = false;
            lblPremiumMessage.Text = Resources.General.NonGGFoundAppDetailSubmission;
            lblPremiumMessage.ForeColor = System.Drawing.Color.Red;
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.NonGGFoundAppDetailSubmission + "');", true);
            return;
        }

        if (chkCompanyStaff.Checked && Session[General.UserRole].ToString() == "100")
        {
            lblPremiumMessage.Text = "You are NOT allowed to update this premium for Company Staff.";
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('You are NOT allowed to update this premium for Company Staff.');", true);
            return;
        }

        DateTime _dtCoverCommDate = dateTimeNow;
        if (DateTime.TryParse(lblEditCoverCommencementDate.Text, out _dtCoverCommDate))
        {
            DateTime _dtNow = new DateTime(dateTimeNow.Year, dateTimeNow.Month, dateTimeNow.Day);

            if (DateTime.Compare(_dtNow, _dtCoverCommDate) > 0)
            {
                lblPremiumError.Text = Resources.General.CommencementCheck;
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.CommencementCheck + "');", true);
                return;
            }
            else
            {
                lblEditCoverCommencementDateCaption.ForeColor = System.Drawing.Color.Gray;
                lblEditCoverCommencementDateMessage.Text = string.Empty;
            }
        }
        else
        {
            lblPremiumError.Text = Resources.General.CommencementCheck;
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.CommencementCheck + "');", true);
            return;
        }

        float _sumInsured = 0.0f;
        if (!float.TryParse(txtOwnDamage.Text, out _sumInsured))
        {
            lblPremiumError.Text = Resources.General.SumInsurredNotValid;
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.SumInsurredNotValid + "');", true);
            return;
        }

        decimal _InstalmentPremiumWOD = 0;
        if (!decimal.TryParse(lblTotalGrossPremiumWOD.Text, out _InstalmentPremiumWOD))
        {
            _InstalmentPremiumWOD = 0;
        }
        if (_InstalmentPremiumWOD <= 0 && ddlPaymentOption.Text == "IP")
        {
            lblPremiumError.Text = Resources.General.PayMsg_NoInstallment;
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.PayMsg_NoInstallment + "');", true);
            return;
        }
        if (!GGSpecialPremiumValidation())
        {
            lblPremiumError.Text = "NCB less then 50%, Can NOT select this premium.";
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('NCB less then 50%, Can NOT select this premium.');", true);
            return;
        }
        Page.Validate("premium");

        if ((Convert.ToInt32(txtPremiumId.Text) > 0) || (Convert.ToInt32(txtPremiumId.Text) <= 0 && grvPremiumList.Rows.Count < 4))
        {
            if (IsValid)
            {
                Int64 _result = 0;
                string _ProductType = "CIN";
                BrokerPremium _brokerPremium = new BrokerPremium();
                BrokerPremiumDB _brokerPremiumdb = new BrokerPremiumDB();

                _brokerPremium.CXBrokerPremiumId = Convert.ToInt64(txtPremiumId.Text);
                _brokerPremium.CXBrokerProviderId = Convert.ToInt64(ddlBrokerProvider.Text);
                _brokerPremium.ProviderCoverTypeId = Convert.ToInt64(ddlBrokerCoverType.Text);
                _brokerPremium.CECarId = Convert.ToInt64(txtCarId.Text);
                _brokerPremium.CustomerId = Convert.ToInt64(txtCustomerId.Text);

                //Changed on 11 Mar 2013 -- Start
                if (Session[General.UserRole] != null && Session[General.UserRole].ToString() == "100")
                {
                    _brokerPremium.AgentId = Convert.ToInt64(txtAgentId.Text);
                }
                else if (ddlAgentbyAdmin.Text != "0")
                {
                    _brokerPremium.AgentId = Convert.ToInt64(ddlAgentbyAdmin.Text);
                }
                else
                {
                    _brokerPremium.AgentId = Convert.ToInt64(txtAgentId.Text);
                }

                _brokerPremium.Premium = Convert.ToSingle(txtNetPremium.Text);

                _brokerPremium.SelectedStatus = chkSelected.Checked;

                _brokerPremium.WorkShop = ddlGarageType.Text;
                _brokerPremium.ProductType = _ProductType;
                _brokerPremium.TotalVMI = Convert.ToSingle(txtGrossPremium.Text);

                _brokerPremium.IsIncludeCMI = chkCTPL.Checked;

                if (chkCTPL.Checked)
                {
                    _brokerPremium.TotalCMI = Convert.ToSingle(txtCTPL.Text);
                }
                else
                {
                    _brokerPremium.TotalCMI = 0;
                }
                _brokerPremium.DiscountPercentage = Convert.ToInt16(ddlDiscountPercentage.Text);


                _brokerPremium.SumInsured = Convert.ToInt32(_sumInsured.ToString("#0"));
                if (_sumInsured > 1000)
                {
                    _brokerPremium.OwnDamage = _sumInsured.ToString("#,000");
                }
                else
                {
                    _brokerPremium.OwnDamage = _sumInsured.ToString("#0");
                }

                _brokerPremium.AnnualPremium = Convert.ToSingle(txtAnnualPremium.Text);

                _brokerPremium.TPPD = txtTPPD.Text;
                _brokerPremium.TPBIP = txtTPBIP.Text;
                _brokerPremium.TPBIA = txtTPBIA.Text;
                _brokerPremium.DEC = txtDeductible.Text;
                _brokerPremium.FireTheft = txtFireTheft.Text;

                _brokerPremium.PADriver = txtPA.Text;
                _brokerPremium.MedicalExpense = txtMED.Text;
                _brokerPremium.BailBound = txtBailBond.Text;

                _brokerPremium.Info1 = lblQRefNo.Text;
                _brokerPremium.Info2 = txtEditLicensePlate.Text;
                _brokerPremium.Info3 = ddlVehicleBodyType.Text;
                _brokerPremium.Info4 = chkCompanyStaff.Checked ? "1" : "0";
                _brokerPremium.Info5 = txtFloodCoverAmount.Text;
                _brokerPremium.Info6 = chkNamedDriver.Checked ? "1" : "0";
                _brokerPremium.Info7 = txtAccModCost.Text;
                _brokerPremium.Info8 = txtPremiumChangeComments.Text;


                _brokerPremium.PaymentOption = "FP";
                if (ddlPaymentOption.Text != "-1")
                {
                    _brokerPremium.PaymentOption = ddlPaymentOption.Text;
                }
                _brokerPremium.NoofInstallment = Convert.ToInt32(ddlNoofInstallments.Text);
                _brokerPremium.Bank = ddlCreditCard.Text;
                float _ipFAPremiumWD = 0.0f;
                if (!float.TryParse(lblTotalGrossPremiumWD.Text, out _ipFAPremiumWD))
                {
                    _ipFAPremiumWD = 0.0f;
                }

                _brokerPremium.IPFinalAnnualPremiumWD = _ipFAPremiumWD;
                _brokerPremium.InstallmentAmountWD = Convert.ToSingle(lblFirstInstallmentWD.Text);
                _brokerPremium.LastInstallmentAmountWD = Convert.ToSingle(lblLastInstallmentWD.Text);
                _brokerPremium.IPFinalAnnualPremiumWOD = Convert.ToSingle(lblTotalGrossPremiumWOD.Text);
                _brokerPremium.InstallmentAmountWOD = Convert.ToSingle(lblFirstInstallmentWOD.Text);
                _brokerPremium.LastInstallmentAmountWOD = Convert.ToSingle(lblLastInstallmentWOD.Text);

                if (ddlPaymentOption.Text == "IP")
                {
                    if (_ipFAPremiumWD > 0)
                    {
                        _brokerPremium.FinalAnnualPremium = _brokerPremium.IPFinalAnnualPremiumWD;
                    }
                    else
                    {
                        _brokerPremium.FinalAnnualPremium = _brokerPremium.IPFinalAnnualPremiumWOD;
                    }
                    _brokerPremium.FinalAnnualPremiumNoDisc = _brokerPremium.IPFinalAnnualPremiumWOD;

                    _brokerPremium.FinalAnnualPremiumWD = Convert.ToSingle(txtFinalAnnualPremium.Text);
                    _brokerPremium.FinalAnnualPremiumWOD = Convert.ToSingle(txtFinalAnnualPremiumNoDisc.Text);
                }
                else
                {
                    if (chkGetTesco.Checked == false)
                    {
                        _brokerPremium.FinalAnnualPremium = Convert.ToSingle(txtFinalAnnualPremium.Text);
                        _brokerPremium.FinalAnnualPremiumWD = Convert.ToSingle(txtFinalAnnualPremium.Text);
                        
                    }
                    else
                    {
                        Single tescoAmt = Convert.ToSingle(txtTescoAmount.Text);
                        _brokerPremium.FinalAnnualPremium = Convert.ToSingle(txtFinalAnnualPremium.Text) + tescoAmt;
                        _brokerPremium.FinalAnnualPremiumWD = Convert.ToSingle(txtFinalAnnualPremium.Text) + tescoAmt;
                    }

                    _brokerPremium.FinalAnnualPremiumNoDisc = Convert.ToSingle(txtFinalAnnualPremiumNoDisc.Text);
                    _brokerPremium.FinalAnnualPremiumWOD = Convert.ToSingle(txtFinalAnnualPremiumNoDisc.Text);
                }

                _brokerPremium.OriginalPremiumWD = Convert.ToSingle(lblB4EditFinalAnnualPremium.Text);
                _brokerPremium.OriginalPremiumWOD = Convert.ToSingle(lblB4EditFinalAnnualPremiumNoDisc.Text);
                _brokerPremium.ApprovedPremium = _brokerPremium.FinalAnnualPremium;
                _brokerPremium.TescoAmount = Convert.ToSingle(txtTescoAmount.Text);
                if (chkGetTesco.Checked)
                {
                    _brokerPremium.TescoSelect = 2;
                }
                else
                {
                    _brokerPremium.TescoSelect = 0;
                }

                _brokerPremium.Approved = 0;

                _brokerPremium.PaymentMode = ddlPaymentMode.SelectedValue;

                //Yui@22/01/2015
                _brokerPremium.Mile = chkMile.Checked;
                //Yui@2/02/2015
                _brokerPremium.EditPremium = chkChangePremium.Checked;

                _result = _brokerPremiumdb.Insert(_brokerPremium);
                if (_result > 0)
                {
                    //if (txtWorldCupDis.Text != "" || txtWorldCupDis.Text != "0" || txtWorldCupDis.Text != "0.00")
                    //{
                    //    Int64 _wcresult = -1;
                    //    MyDatabase _db = new MyDatabase();
                    //    string _spName = "sprocWorldCupContestUpdateDiscount";
                    //    SortedList _sPara = new SortedList();
                    //    _sPara.Add("@WCUserId", hidWCId.Value);
                    //    _sPara.Add("@QuoteRefNo", lblQRefNo.Text);
                    //    _sPara.Add("@WorldCupDiscount", txtWorldCupDis.Text);
                    //    _sPara.Add("@CXBrokerPremiumId", _result.ToString());
                    //    _wcresult = _db.ExecuteSP(_spName, _sPara);
                    //}

                    if (chkSelected.Checked)
                    {
                        lblSelectedRefNo.Text = lblQRefNo.Text;
                    }
                    chkConfirmEmail.Checked = false;
                    chkConfirmEmail_CheckedChanged(sender, e);
                    lblSendQuotationMessage.Text = string.Empty;

                    txtPremiumId.Text = _result.ToString();
                    lblPremiumError.Text = "";
                    lblPremiumMessage.Text = "Successfully Updated";

                    grvPremiumList.DataBind();
                    if (grvPremiumList.Rows.Count > 0)
                    {

                        btnPremiumDownload.Visible = true;
                        lblAppStatusMessage.Text = "( " + grvPremiumList.Rows.Count.ToString() + " ) record(s) found.";
                    }
                    else
                    {
                        lblAppStatusMessage.Text = "No records found.";

                        hplPremiumDownLoad.Visible = false;

                    }
                    hplPremiumDownLoad.NavigateUrl = "PremiumDownload.aspx?carid=" + txtCarId.Text;
                }
                else
                {
                    txtPremiumId.Text = "0";
                    lblPremiumError.Text = "Updated Failed";
                    lblPremiumMessage.Text = "";
                }
            }
        }
        else
        {
            lblPremiumError.Text = "Please create only MAX 4 quotations!";
        }
    }

    private void LoadNoofPaylist()
    {
        try
        {
            txtNoofPayment.Text = "0";
            Int32 NoofRecords = 0;
            DataSet _dsValid = new DataSet();
            _dsValid = GetPaymentsList();
            if (_dsValid != null && _dsValid.Tables.Count > 0)
            {
                if (_dsValid.Tables[0].Rows.Count > 0)
                {
                    NoofRecords += _dsValid.Tables[0].Rows.Count;
                }
                if (_dsValid.Tables.Count > 1 && _dsValid.Tables[1].Rows.Count > 0)
                {
                    NoofRecords += _dsValid.Tables[1].Rows.Count;
                }
                txtNoofPayment.Text = NoofRecords.ToString();
            }
        }
        catch (Exception ex)
        {
        }
    }

    public DataSet GetPaymentsList()
    {
        DataSet _ds = new DataSet();
        if (txtCarId.Text != string.Empty && txtCarId.Text != "0")
        {
            MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
            SortedList _sPara = new SortedList();
            string _spName = "sprocCXCRMPaymentSelectItemListByCECarId";
            _sPara.Add("@CECarId", Convert.ToInt64(txtCarId.Text.Trim()));
            _ds = _db.GetDataSet(_spName, _sPara);
        }
        return _ds;
    }

    private bool ShowScreen(Int64 AgentLeadID, Int16 CallType, Int64 CarID, Int64 CustomerID)
    {
        //DIFFERENT - NON-GG PACKAGES
        //Car ID and Customer ID got from Query String

        bool _retValue = false;
        try
        {
            if (CustomerID > 0)
            {
                txtUserTypeId.Text = GetUserTypeId(CustomerID).ToString();

                if (txtUserTypeId.Text == "1001")
                {
                    CarUserAccount _account = new CarUserAccount();
                    CarUserAccountDB _accountDB = new CarUserAccountDB();

                    _account = _accountDB.GetAccount(Convert.ToInt64(CustomerID));

                    if (_account != null)
                    {
                        if (_account.Status == false)
                        {
                            //REDIRECT
                            _account = null;
                            _accountDB = null;

                            hplReRunQuote.NavigateUrl = "callme-newlead-quotes.aspx?leadid=" + AgentLeadID.ToString() + "&callmeid=" + "0" + "&calltype=" + CallType.ToString() + "&carid=" + CarID.ToString() + "&custid=" + CustomerID;
                            Response.Redirect(hplReRunQuote.NavigateUrl);
                        }
                    }
                }
            }

            string _spName = "sprocCXCRMGetCarDetailSelectSingleItemByAgentLeadID";
            MyDatabase _db = new MyDatabase();
            DataTable _dtCarDetail = new DataTable("tblCar");
            SortedList _paraList = new SortedList();
            _paraList.Add("@AgentLeadID", AgentLeadID);
            _paraList.Add("@CallType", lblCallType.Text);
            _paraList.Add("@LangOption", lblLangOption.Text);
            _dtCarDetail = _db.GetDataTableBySP(_spName, _paraList);
            if (_dtCarDetail != null && _dtCarDetail.Rows.Count > 0)
            {
                LoadControlData();
                txtPromotion.Text = "";
                lblDiscountTen.Text = "";
                if (_dtCarDetail.Rows[0]["Promotion"] != DBNull.Value)
                {
                    if (_dtCarDetail.Rows[0]["Promotion"].ToString() == "3")
                    {
                        txtPromotion.Text = _dtCarDetail.Rows[0]["Promotion"].ToString();
                        lblDiscountTen.Text = "Discount 10%";
                    }
                }

                lblAgentLeadID.Text = _dtCarDetail.Rows[0][0].ToString();
                txtCarId.Text = CarID.ToString();
                txtCustomerId.Text = CustomerID.ToString();

                if (lblCallType.Text == "101" || lblCallType.Text == "102")
                {
                    txtCallMeId.Text = _dtCarDetail.Rows[0][5].ToString();
                }
                else if (lblCallType.Text == "100" && _dtCarDetail.Columns.Contains("PromotionId"))
                {
                    if (_dtCarDetail.Rows[0]["PromotionId"].ToString() != "")
                        hidPromotionId.Value = _dtCarDetail.Rows[0]["PromotionId"].ToString();
                }

                divCarDetailList.Visible = true;
                GetCarDetailList();

                if (lblCallType.Text == "101" || lblCallType.Text == "102")
                {
                    lblCallSessionName.Text += "<td>" + Resources.CarInsurance.CarId + "</td><td><b style='color:red;'>" + _dtCarDetail.Rows[0][2].ToString() + "</b></td>";
                    lblCallSessionName.Text += "<td><b style='color:blue;'> CALL ME ID</td><td>" + _dtCarDetail.Rows[0][5].ToString() + "</b></td>";
                    lblCallSessionName.Text += "<td>" + Resources.CarInsurance.CallTime + "</td><td><b style='color:green;'>" + _dtCarDetail.Rows[0][7].ToString() + "</b></td>";
                    if (_dtCarDetail.Columns.Count > 9)
                        lblCallSessionName.Text += "<td>" + Resources.CarInsuranceResultPage.Insurer + "</td><td><b style='color:blue;'>" + _dtCarDetail.Rows[0][10].ToString() + "</b></td>";
                    if (_dtCarDetail.Columns.Count > 7)
                        lblCallSessionName.Text += "<td>" + Resources.General.Requestedon + "</td><td><b style='color:red;'>" + Convert.ToDateTime(_dtCarDetail.Rows[0][8].ToString()).ToString("dd/MMM/yyyy hh:mm:ss tt") + "</b></td>";
                    lblCallSessionName.Text += "</tr></table>";
                }
                else
                {
                    if (!_dtCarDetail.Columns.Contains("PromotionId"))
                    {
                        lblCallSessionName.Text += "</tr></table>";
                    }
                    else if (lblCallType.Text == "100" && _dtCarDetail.Columns.Contains("PromotionId"))
                    {
                        if (_dtCarDetail.Rows[0]["PromotionId"].ToString() != "")
                        {
                            //28March2014
                            lblCallSessionName.Text += "</tr></table>";
                            hidPromotionId.Value = _dtCarDetail.Rows[0]["PromotionId"].ToString();
                            GetPromotion();
                        }
                    }
                }

                ShowFirstOrderConfirmationSendDate(CarID, CustomerID);
                ShowLastQuotationSendDate(CarID, CustomerID);
                ShowLastOrderConfirmationSendDate(CarID, CustomerID);

                //Yui@04Sept2014
                if (Session[General.IsRenewalAgent].ToString() != "1") CheckFirstQuote();
                //**************
                CheckApplicationStatus();

                _retValue = true;
            }
            else
            {
                _retValue = false;
            }
        }
        catch (Exception Ex)
        {
            _retValue = false;
            lblCallSessionName.Text += "<br/><b style='color:red;'>" + Resources.General.ERROR + "</b>: at ShowScreen(Int64 AgentLeadID, Int16 CallType)<br/>" + Ex.Message + "<br/><br/>" + Ex.StackTrace;

        }

        return _retValue;
    }

    private bool ShowScreen()
    {
        bool _retValue = false;
        try
        {
            string _spName = "sprocCXCRMGetCarDetailSelectSingleItem";
            MyDatabase _db = new MyDatabase();
            DataTable _dtCarDetail = new DataTable("tblCar");
            SortedList _paraList = new SortedList();
            _paraList.Add("@AgentID", Session[General.UserId].ToString());
            _paraList.Add("@CallType", lblCallType.Text);
            _paraList.Add("@LangOption", lblLangOption.Text);

            _dtCarDetail = _db.GetDataTableBySP(_spName, _paraList);
           
            if (_dtCarDetail != null && _dtCarDetail.Rows.Count > 0)
            {
                string _agentLeadID = _dtCarDetail.Rows[0][0].ToString();
                string _carID = _dtCarDetail.Rows[0][2].ToString();
                string _customerID = _dtCarDetail.Rows[0][1].ToString();

                MyDatabase _myDb = new MyDatabase();
                object _promotion = _myDb.ExecuteScalarSqlStatement("SELECT Ninfo4 FROM tblCXCRMAgentLeads WHERE AgentLeadID = " + _agentLeadID);
                txtPromotion.Text = "";
                lblDiscountTen.Text = "";
                if (_promotion != null)
                {
                    if (_promotion.ToString() == "3")
                    {
                        txtPromotion.Text = _promotion.ToString();
                        lblDiscountTen.Text = "Discount 10%";
                    }
                }
                 //Yui@02062014
                if (_dtCarDetail.Rows[0][6].ToString() == "100")
                    if (CheckMobile(_carID, _agentLeadID))
                        return false;

                if (_carID == "0" && _customerID == "0")
                {
                    if (_dtCarDetail.Rows[0][5] != DBNull.Value && Convert.ToInt32(_dtCarDetail.Rows[0][5].ToString()) > 0)
                    {
                        Response.Redirect("~/carinsurance/ViewCICustomerCallNewSearch.aspx?leadid=" + _agentLeadID + "&callmeid=" + _dtCarDetail.Rows[0][5].ToString() + "&calltype=" + _dtCarDetail.Rows[0][6].ToString());
                    }
                    else
                    {
                        if (_dtCarDetail.Rows[0][6] != DBNull.Value && _dtCarDetail.Rows[0][6].ToString() == "103")
                        {
                            Response.Redirect("~/carinsurance/offline/callme-newlead-quotes.aspx?leadid=" + _agentLeadID + "&callmeid=0&calltype=" + _dtCarDetail.Rows[0][6].ToString() + "&carid=0&custid=0");
                        }
                        else
                        {
                            lblCallSessionName.Text += "<br/>" + Resources.General.CallMeBack + " - " + Resources.General.FAIL;
                        }
                    }
                }
                else if (_carID == "0" && _customerID != "0" && (_dtCarDetail.Rows[0][6] != DBNull.Value && _dtCarDetail.Rows[0][6].ToString() == "100") && _dtCarDetail.Columns.Contains("PromotionId"))
                {
                    //28March2014
                    Response.Redirect("~/carinsurance/offline/callme-newlead-quotes.aspx?leadid=" + _agentLeadID + "&callmeid=0&calltype=" + _dtCarDetail.Rows[0][6].ToString() + "&carid=0&custid=" + _dtCarDetail.Rows[0][1].ToString() + "&proid=" + _dtCarDetail.Rows[0]["PromotionId"].ToString());
                }
                else if (_carID == "0" && _customerID != "0" && (_dtCarDetail.Rows[0][6] != DBNull.Value && _dtCarDetail.Rows[0][6].ToString() == "101") && _dtCarDetail.Columns.Contains("CallMeId"))
                {
                    //28March2014
                    Response.Redirect("~/carinsurance/offline/callme-newlead-quotes.aspx?leadid=" + _agentLeadID + "&callmeid=" + _dtCarDetail.Rows[0]["CallMeId"].ToString() + "&calltype=" + _dtCarDetail.Rows[0][6].ToString() + "&carid=0&custid=" + _dtCarDetail.Rows[0][1].ToString());
                }
                else
                {
                    if (Convert.ToInt64(_customerID) > 0)
                    {
                        txtUserTypeId.Text = GetUserTypeId(Convert.ToInt64(_customerID)).ToString();
                    }
                    Int16 _usrTypeID = 400;
                    Int16 _callTypeID = Convert.ToInt16(_dtCarDetail.Rows[0][6].ToString());

                    if (_callTypeID == 100)
                    {
                        if (_dtCarDetail.Columns.Contains("UsrTypeID"))
                            _usrTypeID = Convert.ToInt16(_dtCarDetail.Rows[0][7].ToString());
                    }

                    if (_usrTypeID == 1001)
                    {
                        CarUserAccount _account = new CarUserAccount();
                        CarUserAccountDB _accountDB = new CarUserAccountDB();

                        _account = _accountDB.GetAccount(Convert.ToInt64(_customerID));

                        if (_account != null)
                        {
                            if (_account.Status == false)
                            {
                                //REDIRECT
                                _account = null;
                                _accountDB = null;

                                hplReRunQuote.NavigateUrl = "callme-newlead-quotes.aspx?leadid=" + _agentLeadID + "&callmeid=" + "0" + "&calltype=" + "100" + "&carid=" + _carID + "&custid=" + _customerID;
                                Response.Redirect(hplReRunQuote.NavigateUrl);
                            }
                        }
                    }

                    LoadControlData();

                    lblAgentLeadID.Text = _agentLeadID;

                    txtCarId.Text = _carID;

                    txtCustomerId.Text = _customerID;

                    lblCallType.Text = _dtCarDetail.Rows[0][6].ToString();

                    ShowCallTypeDesc();

                    if (lblCallType.Text == "101" || lblCallType.Text == "102")
                    {
                        txtCallMeId.Text = _dtCarDetail.Rows[0][5].ToString();
                    }
                    else if (lblCallType.Text == "100" && _dtCarDetail.Columns.Contains("PromotionId"))
                    {
                        if (_dtCarDetail.Rows[0]["PromotionId"].ToString() != "")
                            hidPromotionId.Value = _dtCarDetail.Rows[0]["PromotionId"].ToString();
                    }

                    divCarDetailList.Visible = true;
                    GetCarDetailList();

                    if (lblCallType.Text == "101" || lblCallType.Text == "102")
                    {
                        lblCallSessionName.Text += "<td>" + Resources.CarInsurance.CarId + "</td><td><b style='color:red;'>" + _dtCarDetail.Rows[0][2].ToString() + "</b></td>";
                        lblCallSessionName.Text += "<td><b style='color:blue;'> CALL ME ID</td><td>" + _dtCarDetail.Rows[0][5].ToString() + "</b></td>";
                        lblCallSessionName.Text += "<td>" + Resources.CarInsurance.CallTime + "</td><td><b style='color:green;'>" + _dtCarDetail.Rows[0][7].ToString() + "</b></td>";
                        if (_dtCarDetail.Columns.Count > 9)
                            lblCallSessionName.Text += "<td>" + Resources.CarInsuranceResultPage.Insurer + "</td><td><b style='color:blue;'>" + _dtCarDetail.Rows[0][10].ToString() + "</b></td>";
                        if (_dtCarDetail.Columns.Count > 7)
                            lblCallSessionName.Text += "<td>" + Resources.General.Requestedon + "</td><td><b style='color:red;'>" + Convert.ToDateTime(_dtCarDetail.Rows[0][8].ToString()).ToString("dd/MMM/yyyy hh:mm:ss tt") + "</b></td>";
                        lblCallSessionName.Text += "</tr></table>";
                    }
                    else
                    {
                        if (!_dtCarDetail.Columns.Contains("PromotionId"))
                        {
                            lblCallSessionName.Text += "</tr></table>";
                        }
                        else if (lblCallType.Text == "100" && _dtCarDetail.Columns.Contains("PromotionId"))
                        {
                            if (_dtCarDetail.Rows[0]["PromotionId"].ToString() != "")
                            {
                                //28March2014
                                lblCallSessionName.Text += "</tr></table>";
                                hidPromotionId.Value = _dtCarDetail.Rows[0]["PromotionId"].ToString();
                                GetPromotion();
                            }
                        }
                    }

                    ShowFirstOrderConfirmationSendDate(Convert.ToInt64(txtCarId.Text), Convert.ToInt64(txtCustomerId.Text));
                    ShowLastQuotationSendDate(Convert.ToInt64(txtCarId.Text), Convert.ToInt64(txtCustomerId.Text));
                    ShowLastOrderConfirmationSendDate(Convert.ToInt64(txtCarId.Text), Convert.ToInt64(txtCustomerId.Text));

                    //Yui@04Sept2014
                    if (Session[General.IsRenewalAgent].ToString() != "1") CheckFirstQuote();
                    //**************

                    CheckApplicationStatus();

                    _retValue = true;
                }
            }
            else
            {
                _retValue = false;
            }
        }
        catch (Exception Ex)
        {
            _retValue = false;
            lblCallSessionName.Text += "<br/><b style='color:red;'>" + Resources.General.ERROR + "</b>: at ShowScreen()<br/>" + Ex.Message + "<br/><br/>" + Ex.StackTrace;

        }

        return _retValue;
    }

    private void GetCustomerUserId()
    {
        try
        {
            string userid = "";
            if (txtCustomerId.Text.Trim() != "")
            {
                MyDatabase _myDb = new MyDatabase();
                object _userid = _myDb.ExecuteScalarSqlStatement("SELECT UserId FROM tblCEUser WHERE UserId = 'CEUSERAUTOHA' AND CEID = " + txtCustomerId.Text.Trim());
                if (_userid != null)
                    userid = _userid.ToString();
            }

            if (userid.Trim() == "CEUSERAUTOHA")
                lblOtherCustomer.Text = "ลูกค้าไม่ได้มาจาก GluayGluay.com";
        }
        catch (Exception)
        {
        }
        //lblOtherCustomer
    }

    #region CheckMobile

    private bool CheckMobile(string CarId, string AgentLeadId)
    {
        //tblcardetailth.binfo2 for keeping the status that the record was already update (for mobile only).
        MyDatabase _myDb = new MyDatabase();
        object runVal = _myDb.ExecuteScalarSqlStatement(@"SELECT p.Info8 FROM tblCarPolicy p INNER JOIN tblcardetailth d ON p.cecarid = d.carid
                INNER JOIN tblMobileCarInquiryDetails m ON p.cecarid = m.carid
                WHERE d.binfo2 IS NULL AND p.CECARID = " + CarId.ToString());
        //LEFT OUTER JOIN tblCXCRMCallStatus s ON  p.RefCEUserId = s.CustomerId AND CallTypeId = 100 
        if (runVal != null)
        {
            // Mobile & Not update
            // New : No Call Status (tblCXCRMCallStatus)
            string strQuoteCode = runVal.ToString().ToUpper();

            if (strQuoteCode == "MOBILE")
            {
                string redirectUrl = "callme-newlead-quotes.aspx?leadid=" + AgentLeadId + "&callmeid=" + "0" + "&calltype=" + "100" + "&carid=" + CarId + "&custid=100&ismobile=1";
                Response.Redirect(redirectUrl, false);
                return true;
            }
        }

        return false;
    }

    #endregion

    #region Promotion

    private void GetPromotion()
    {
        PromotionGGDB objPro = new PromotionGGDB();
        DataTable _dt = objPro.GetPromotion(Int64.Parse(hidPromotionId.Value));
        if (_dt.Rows.Count > 0)
        {
            ltrPromotion.Text = "<table border=\"0\" style=\"width:100%\">";
            foreach (DataRow drPro in _dt.Rows)
            {
                ltrPromotion.Text += "<tr>";
                ltrPromotion.Text += "<td>Promotion:</td><td colspan=\"5\"><b style='color:red;'>" + drPro["PromotionName"].ToString() + "</b></td>";
                ltrPromotion.Text += "</tr>";
                ltrPromotion.Text += "<tr>";
                System.Globalization.CultureInfo cul = new System.Globalization.CultureInfo("th-TH");
                ltrPromotion.Text += "<td>" + Resources.CarInsurance.CoverCommencementDate + ":</td><td><b style='color:blue;'>" + cul.DateTimeFormat.GetMonthName(int.Parse(drPro["CommencementMonth"].ToString())) + "</b></td>";
                ltrPromotion.Text += "<td>" + Resources.CarInsurance.CallTime + ":</td><td><b style='color:green;'>" + GetCallAt(int.Parse(drPro["CallAt"].ToString())) + "</b></td>";
                ltrPromotion.Text += "<td>" + Resources.General.Requestedon + ":</td><td><b style='color:red;'>" + Convert.ToDateTime(drPro["CreatedDate"].ToString()).ToString("dd/MMM/yyyy hh:mm:ss tt") + "</b></td>";
                ltrPromotion.Text += "</tr>";
            }
            ltrPromotion.Text += "</table>";
        }
    }

    private string GetCallAt(int callAt)
    {
        switch (callAt)
        {
            case 1:
                return "ตอนเช้า";
            case 2:
                return "ตอนบ่าย";
            case 3:
                return "ตอนเย็น";
            case 4:
                return "ทุกเวลา";
            default:
                return "";
        }
    }

    #endregion

    private void ShowCallTypeDesc()
    {
        if (lblCallType.Text == "100")
        {

            lblCallTypeDesc.Text = Resources.General.FirstFollowUpCall;
            lblLastCallStatusCaption.Text = Resources.General.FirstFollowUpCall + " - " + Resources.General.LastCallStatus;
        }
        else if (lblCallType.Text == "101")
        {
            lblCallTypeDesc.Text = Resources.General.CallMeRequest;
            lblLastCallStatusCaption.Text = Resources.General.CallMeRequest + " - " + Resources.General.LastCallStatus;
        }
        else if (lblCallType.Text == "102")
        {
            lblCallTypeDesc.Text = Resources.General.CallMeBack;
            lblLastCallStatusCaption.Text = Resources.General.CallMeBack + " - " + Resources.General.LastCallStatus;
        }
        else if (lblCallType.Text == "103") //102
        {
            lblCallTypeDesc.Text = Resources.General.CallDirect;
            lblLastCallStatusCaption.Text = Resources.General.CallDirect + " - " + Resources.General.LastCallStatus;
        }
        lblCallTypeDesc.Text += ShowQuoteFrom();
    }

    private string ShowQuoteFrom()
    {
        string QuoteFrom = "";
        if (Request.Params["carid"] != null)
        {
            Int64 CarId = 0;
            if (!Int64.TryParse(Request.Params["carid"].ToString(), out CarId))
            {
                CarId = 0;
            }

            MyDatabase _myDb = new MyDatabase();
            object runVal = _myDb.ExecuteScalarSqlStatement(@"SELECT Info8 FROM TBLCARPOLICY WHERE CECARID = " + CarId.ToString());

            if (runVal != null)
            {
                string strQuoteCode = runVal.ToString().ToUpper();

                if (strQuoteCode == "MOBILE")
                {
                    QuoteFrom = " (" + Resources.Menu.Mobile + ")";
                }
                else if (strQuoteCode == "CLAIM")
                {

                    QuoteFrom = " (" + Resources.General.Claims + ")";
                }
            }
        }
        return QuoteFrom;
    }

    protected void ShowCarAndCustomerDetails(Int64 CustomerID, Int64 CarID, Int64 CarPolicyID)
    {
        if (CustomerID > 0 && CarID > 0 && CarPolicyID > 0)
        {
            txtCustomerId.Text = CustomerID.ToString();
            txtCarId.Text = CarID.ToString();

            //POLICY ID IS ONLY NEEDED FOR RE-RUN QUOTE
            txtCarPolicyId.Text = CarPolicyID.ToString();

            txtCICallMeRemark.Visible = false;
            lblRefCarID.Text = CarID.ToString();

            //Checking Application Summary
            MyDatabase _myDb = new MyDatabase();
            SortedList _paraList = new SortedList();
            _paraList.Add("@CECarID", CarID);
            _paraList.Add("@CustomerID", CustomerID);
            DataTable _dtApp = new DataTable("tblApp");
            _dtApp = _myDb.GetDataTableBySP("sprocCXCRMNonGGApplicationStatusSelectItem", _paraList);
            if (_dtApp != null && _dtApp.Rows.Count > 0)
            {
                if (_dtApp.Rows[0]["Completed"].ToString() == "1")
                {
                    lblLastYearRefNo.Text = _dtApp.Rows[0]["QuoteRefNo"].ToString();
                    lblRenewalStaus.Text = "1";
                    btnRenewalQuote.Text = "Renewal Quote";
                    btnRenewalQuote.Visible = true;
                    divLinks.Visible = true;
                    divCarDetailList.Visible = false;

                    btnSendOrderConfirmation.Visible = false;
                    btnNewPremium.Visible = false;
                    btnSendQuotation.Visible = false;
                    txtConfirmEmail.Visible = false;
                    btnNewPremiumTwo.Visible = false;

                    if (Session[General.UserRole].ToString() == "100")
                    {
                        btnRenewalQuote.Enabled = false;
                    }
                }
            }

            if (btnRenewalQuote.Visible == false)
            {
                #region Check Selected And Completed

                object IsMobile = _myDb.ExecuteScalarSqlStatement(@"SELECT p.Info8 FROM tblCarPolicy p
                INNER JOIN tblMobileCarInquiryDetails m ON p.cecarid = m.carid
                WHERE p.CECARID = " + CarID);

                bool _isMobile = false;
                if (IsMobile != null)
                {
                    if (IsMobile.ToString().ToUpper() == "MOBILE")
                    {
                        _isMobile = true;
                        
                        Int64 _providerCompanyId = 0;

                        SortedList _sqlParam = new SortedList();
                        _sqlParam.Add("@CarID", txtCarId.Text);
                        DataTable _dtMobileCompltedQuote = _myDb.GetDataTableBySP("sprocMobileSelectedCompletedUserSelectItem", _sqlParam);

                        if (_dtMobileCompltedQuote != null && _dtMobileCompltedQuote.Rows.Count > 0)
                        {
                            divCompletedQuoteDetails.Visible = true;
                            lblApplicationFormSummaryCaption.Text += lblApplicationFormSummaryCaption.Text + " (Mobile)";

                            lblCQFullName.Text = _dtMobileCompltedQuote.Rows[0]["Name"].ToString();
                            lblCQQuoteRefNo.Text = "";
                            if (lblCQQuoteRefNo.Text.Trim().Length > 4 && lblCQQuoteRefNo.Text.Trim().Substring(0, 2) == "GG")
                            {
                                txtGG.Text = "GGSPECIAL";
                            }
                            else
                            {
                                if (txtGG.Text == "GGSPECIAL") txtGG.Text = "";
                            }
                            lblCQPaymentType.Text = _dtMobileCompltedQuote.Rows[0]["Payment"].ToString();

                            lblCQOrderRefNo.Text = "";
                            lblCQPackageName.Text = _dtMobileCompltedQuote.Rows[0]["CoverTypeDesc"].ToString();
                            lblCQPremiumAmount.Text = _dtMobileCompltedQuote.Rows[0]["PAnnualPremium"].ToString();
                            lblCQCTPLStatus.Text = _dtMobileCompltedQuote.Rows[0]["IsCTPL"].ToString();

                            lblCQDateTime.Text = Convert.ToDateTime(_dtMobileCompltedQuote.Rows[0]["ModifiedDate"].ToString()).ToString("dd-MMM-yyyy hh:mm:ss tt");
                            ClientScript.RegisterStartupScript(this.GetType(), "JS_CompletedQuoteAlert", "alert(' " + Resources.CarInsurance.CarId + ": " + txtCarId.Text + " - " + Resources.General.AppFromGGOnline + " (Mobile)" + "');", true);

                            //**************************************************************************************

                            _providerCompanyId = Convert.ToInt64(_dtMobileCompltedQuote.Rows[0]["ProviderCompanyID"].ToString());
                            float _totalVMI = Convert.ToSingle(_dtMobileCompltedQuote.Rows[0]["TotalVMI"].ToString());

                            ddlBrokerProvider.SelectedIndex = ddlBrokerProvider.Items.IndexOf(ddlBrokerProvider.Items.FindByValue(_providerCompanyId.ToString()));
                            ddlBrokerProvider_SelectedIndexChanged(null, null);
                            ddlBrokerCoverType.Text = _dtMobileCompltedQuote.Rows[0]["InsuranceType"].ToString();
                            //Yui@22/01/2015
                            chkMile.Checked = false;
                            if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11")
                                chkMile.Enabled = true;
                            else
                                chkMile.Enabled = false;

                            if (txtPremiumId.Text == "0")
                            {
                                ddlGarageType.Text = _dtMobileCompltedQuote.Rows[0]["GarageType"].ToString();

                                if (_dtMobileCompltedQuote.Rows[0]["TPBIA"] != DBNull.Value)
                                {
                                    txtTPBIA.Text = Convert.ToSingle(_dtMobileCompltedQuote.Rows[0]["TPBIA"].ToString()).ToString("#,000");
                                }
                                else
                                {
                                    txtTPBIA.Text = "N/A";
                                }

                                if (_dtMobileCompltedQuote.Rows[0]["TPBIP"] != DBNull.Value)
                                {
                                    txtTPBIP.Text = Convert.ToSingle(_dtMobileCompltedQuote.Rows[0]["TPBIP"].ToString()).ToString("#,000");
                                }
                                else
                                {
                                    txtTPBIP.Text = "N/A";
                                }

                                if (_dtMobileCompltedQuote.Rows[0]["TPPD"] != DBNull.Value)
                                {
                                    txtTPPD.Text = Convert.ToSingle(_dtMobileCompltedQuote.Rows[0]["TPPD"].ToString()).ToString("#,000");
                                }
                                else
                                {
                                    txtTPPD.Text = "N/A";
                                }

                                if (_dtMobileCompltedQuote.Rows[0]["DEC"] != DBNull.Value)
                                {
                                    txtDeductible.Text = Convert.ToSingle(_dtMobileCompltedQuote.Rows[0]["DEC"].ToString()).ToString("#0");
                                }

                                if (_dtMobileCompltedQuote.Rows[0]["PADriver"] != DBNull.Value)
                                {
                                    txtPA.Text = Convert.ToSingle(_dtMobileCompltedQuote.Rows[0]["PADriver"].ToString()).ToString("#,000");
                                }
                                else
                                {
                                    txtPA.Text = "N/A";
                                }

                                if (_dtMobileCompltedQuote.Rows[0]["BailBond"] != DBNull.Value)
                                {
                                    txtBailBond.Text = Convert.ToSingle(_dtMobileCompltedQuote.Rows[0]["BailBond"].ToString()).ToString("#,000");
                                }
                                else
                                {
                                    txtBailBond.Text = "N/A";
                                }

                                if (_dtMobileCompltedQuote.Rows[0]["MedicalExpense"] != DBNull.Value)
                                {
                                    txtMED.Text = Convert.ToSingle(_dtMobileCompltedQuote.Rows[0]["MedicalExpense"].ToString()).ToString("#,000");
                                }
                                else
                                {
                                    txtMED.Text = "N/A";
                                }

                                txtGrossPremium.Text = _totalVMI.ToString("#000.00");

                                float _totalCMI = 0.0f;
                                if (_dtMobileCompltedQuote.Rows[0]["IsInCludeCMI"] != DBNull.Value)
                                {
                                    if (_dtMobileCompltedQuote.Rows[0]["IsInCludeCMI"].ToString().ToLower() == "yes")
                                    {
                                        _totalCMI = Convert.ToSingle(_dtMobileCompltedQuote.Rows[0]["IsInCludeCMI"].ToString());
                                        chkCTPL.Checked = true;
                                    }
                                    else
                                    {
                                        chkCTPL.Checked = false;
                                    }
                                }

                                txtGrossPremium_TextChanged(null, null);
                            }
                        }
                    }
                }

                if (!_isMobile)
                {
                    // Web
                    Int64 _providerCompanyId = 0;
                    DataTable _dtSeletedItem = new DataTable("tblSelect");
                    _dtSeletedItem = _myDb.GetDataTable(@"SELECT P.INSURANCETYPE, P.GarageType, P.IsCTPL, S.* FROM TBLCARINSURANCESELECTITEMTH S
	                                                INNER JOIN TBLCARPOLICY P ON S.CARID = P.CECARID AND P.REFCEUSERID = S.REFCEUSERID 
                                                    Where S.CarID = " + txtCarId.Text + " And S.RefCEUserID = " + txtCustomerId.Text);

                    if (_dtSeletedItem != null && _dtSeletedItem.Rows.Count > 0)
                    {
                        //Yui@5/2/2015
                        //divResultExcel.Visible = false;

                        _providerCompanyId = Convert.ToInt64(_dtSeletedItem.Rows[0]["ProviderCompanyID"].ToString());
                        float _totalVMI = Convert.ToSingle(_dtSeletedItem.Rows[0]["TotalVMI"].ToString());

                        SortedList _sqlParam = new SortedList();
                        _sqlParam.Add("@CarID", txtCarId.Text);
                        _sqlParam.Add("@ProviderCompanyID", _providerCompanyId.ToString());
                        DataTable _dtCompltedQuote = _myDb.GetDataTableBySP("sprocCarInsuranceTHCompletedUserSelectItem", _sqlParam);
                        if (_dtCompltedQuote != null && _dtCompltedQuote.Rows.Count > 0)
                        {
                            divCompletedQuoteDetails.Visible = true;

                            lblCQFullName.Text = _dtCompltedQuote.Rows[0]["Name"].ToString();
                            lblCQQuoteRefNo.Text = _dtCompltedQuote.Rows[0]["QuoteRefNo"].ToString();
                            if (lblCQQuoteRefNo.Text.Trim().Length > 4 && lblCQQuoteRefNo.Text.Trim().Substring(0, 2) == "GG")
                            {
                                txtGG.Text = "GGSPECIAL";
                            }
                            else
                            {
                                if (txtGG.Text == "GGSPECIAL") txtGG.Text = "";
                            }
                            lblCQPaymentType.Text = _dtCompltedQuote.Rows[0]["Payment"].ToString();

                            lblCQOrderRefNo.Text = _dtCompltedQuote.Rows[0]["OrderRefNo"].ToString();
                            lblCQPackageName.Text = _dtCompltedQuote.Rows[0]["CoverTypeDesc"].ToString();
                            lblCQPremiumAmount.Text = _dtCompltedQuote.Rows[0]["PAnnualPremium"].ToString();
                            lblCQCTPLStatus.Text = _dtCompltedQuote.Rows[0]["IsCTPL"].ToString();

                            lblCQDateTime.Text = Convert.ToDateTime(_dtCompltedQuote.Rows[0]["ModifiedDate"].ToString()).ToString("dd-MMM-yyyy hh:mm:ss tt");
                            ClientScript.RegisterStartupScript(this.GetType(), "JS_CompletedQuoteAlert", "alert(' " + Resources.CarInsurance.ReferenceNo + ". \"" + lblCQQuoteRefNo.Text + "\" >> " + Resources.CarInsurance.CarId + ": " + txtCarId.Text + " - " + Resources.General.AppFromGGOnline + "" + "');", true);


                            if (_dtCompltedQuote.Rows[0]["CarPlate"] != DBNull.Value)
                            {
                                txtEditLicensePlate.Text = _dtCompltedQuote.Rows[0]["CarPlate"].ToString().ToUpper();
                                lblEditLicensePlate.Text = _dtCompltedQuote.Rows[0]["CarPlate"].ToString().ToUpper();
                            }
                            
                            //if (txtGG.Text.Trim() == "GGSPECIAL")
                            //{
                            //    DataTable _dtBrokerProvider = General.GetComboItem("BrokerProvider", "CXBrokerProviderId", _providerCompanyId.ToString(), true);
                            //    if (_dtBrokerProvider != null && _dtBrokerProvider.Rows.Count > 0)
                            //    {
                            //        ddlBrokerProvider.Items.Clear();
                            //        ddlBrokerProvider.DataSource = _dtBrokerProvider;
                            //        ddlBrokerProvider.DataTextField = _dtBrokerProvider.Columns[0].ColumnName.ToString();
                            //        ddlBrokerProvider.DataValueField = _dtBrokerProvider.Columns[1].ColumnName.ToString();
                            //        ddlBrokerProvider.DataBind();
                            //        ddlBrokerProvider.Items.Insert(0, new ListItem("Select", "-1"));
                            //    }
                            //}

                            ddlBrokerProvider.SelectedIndex = ddlBrokerProvider.Items.IndexOf(ddlBrokerProvider.Items.FindByValue(_providerCompanyId.ToString()));
                            if (txtGG.Text.Trim() == "GGSPECIAL")
                                ddlBrokerProvider.Enabled = false;
                            else
                                ddlBrokerProvider.Enabled = true;

                            ddlBrokerProvider_SelectedIndexChanged(null, null);
                            ddlBrokerCoverType.Text = _dtSeletedItem.Rows[0]["INSURANCETYPE"].ToString();
                            //Yui@22/01/2015
                            chkMile.Checked = false;
                            if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11")
                                chkMile.Enabled = true;
                            else
                                chkMile.Enabled = false;

                            if (txtPremiumId.Text == "0")
                            {
                                ddlGarageType.Text = _dtSeletedItem.Rows[0]["GarageType"].ToString();


                                if (_dtSeletedItem.Rows[0]["TPBIA"] != DBNull.Value)
                                {
                                    txtTPBIA.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPBIA"].ToString()).ToString("#,000");
                                }
                                else
                                {
                                    txtTPBIA.Text = "N/A";
                                }

                                if (_dtSeletedItem.Rows[0]["TPBIP"] != DBNull.Value)
                                {
                                    txtTPBIP.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPBIP"].ToString()).ToString("#,000");
                                }
                                else
                                {
                                    txtTPBIP.Text = "N/A";
                                }

                                if (_dtSeletedItem.Rows[0]["TPPD"] != DBNull.Value)
                                {
                                    txtTPPD.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPPD"].ToString()).ToString("#,000");
                                }
                                else
                                {
                                    txtTPPD.Text = "N/A";
                                }

                                if (_dtSeletedItem.Rows[0]["DEC"] != DBNull.Value)
                                {
                                    txtDeductible.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["DEC"].ToString()).ToString("#0");
                                }

                                if (_dtSeletedItem.Rows[0]["PADriver"] != DBNull.Value)
                                {
                                    txtPA.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["PADriver"].ToString()).ToString("#,000");
                                }
                                else
                                {
                                    txtPA.Text = "N/A";
                                }

                                if (_dtSeletedItem.Rows[0]["BailBond"] != DBNull.Value)
                                {
                                    txtBailBond.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["BailBond"].ToString()).ToString("#,000");
                                }
                                else
                                {
                                    txtBailBond.Text = "N/A";
                                }

                                if (_dtSeletedItem.Rows[0]["MedExp"] != DBNull.Value)
                                {
                                    txtMED.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["MedExp"].ToString()).ToString("#,000");
                                }
                                else
                                {
                                    txtMED.Text = "N/A";
                                }

                                txtGrossPremium.Text = _totalVMI.ToString("#000.00");

                                float _totalCMI = 0.0f;
                                if (_dtCompltedQuote.Rows[0]["IsCTPL"] != DBNull.Value)
                                {
                                    if (_dtCompltedQuote.Rows[0]["IsCTPL"].ToString().ToLower() == "yes")
                                    {
                                        _totalCMI = Convert.ToSingle(_dtCompltedQuote.Rows[0]["CTPL"].ToString());
                                        chkCTPL.Checked = true;
                                    }
                                    else
                                    {
                                        chkCTPL.Checked = false;
                                    }
                                }

                                if (ddlDiscountPercentage.Items.Count == 1) 
                                    LoadDiscountPercentageList();
                                else
                                    txtGrossPremium_TextChanged(null, null);
                            }
                        }
                        else
                        {
                            ddlBrokerProvider.SelectedIndex = ddlBrokerProvider.Items.IndexOf(ddlBrokerProvider.Items.FindByValue(_providerCompanyId.ToString()));
                            ddlBrokerProvider_SelectedIndexChanged(null, null);
                            ddlBrokerCoverType.Text = _dtSeletedItem.Rows[0]["INSURANCETYPE"].ToString();
                            //Yui@22/01/2015
                            chkMile.Checked = false;
                            if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11")
                                chkMile.Enabled = true;
                            else
                                chkMile.Enabled = false;

                            if (txtPremiumId.Text == "0")
                            {
                                ddlGarageType.Text = _dtSeletedItem.Rows[0]["GarageType"].ToString();


                                if (_dtSeletedItem.Rows[0]["TPBIA"] != DBNull.Value)
                                {
                                    txtTPBIA.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPBIA"].ToString()).ToString("#,000");
                                }
                                else
                                {
                                    txtTPBIA.Text = "N/A";
                                }

                                if (_dtSeletedItem.Rows[0]["TPBIP"] != DBNull.Value)
                                {
                                    txtTPBIP.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPBIP"].ToString()).ToString("#,000");
                                }
                                else
                                {
                                    txtTPBIP.Text = "N/A";
                                }

                                if (_dtSeletedItem.Rows[0]["TPPD"] != DBNull.Value)
                                {
                                    txtTPPD.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPPD"].ToString()).ToString("#,000");
                                }
                                else
                                {
                                    txtTPPD.Text = "N/A";
                                }

                                if (_dtSeletedItem.Rows[0]["DEC"] != DBNull.Value)
                                {
                                    txtDeductible.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["DEC"].ToString()).ToString("#0");
                                }

                                if (_dtSeletedItem.Rows[0]["PADriver"] != DBNull.Value)
                                {
                                    txtPA.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["PADriver"].ToString()).ToString("#,000");
                                }
                                else
                                {
                                    txtPA.Text = "N/A";
                                }

                                if (_dtSeletedItem.Rows[0]["BailBond"] != DBNull.Value)
                                {
                                    txtBailBond.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["BailBond"].ToString()).ToString("#,000");
                                }
                                else
                                {
                                    txtBailBond.Text = "N/A";
                                }

                                if (_dtSeletedItem.Rows[0]["MedExp"] != DBNull.Value)
                                {
                                    txtMED.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["MedExp"].ToString()).ToString("#,000");
                                }
                                else
                                {
                                    txtMED.Text = "N/A";
                                }

                                txtGrossPremium.Text = _totalVMI.ToString("#000.00");

                                float _totalCMI = 0.0f;
                                if (_dtSeletedItem.Rows[0]["IsCTPL"] != DBNull.Value)
                                {
                                    if (_dtSeletedItem.Rows[0]["IsCTPL"].ToString().ToLower() == "true")
                                    {
                                        _totalCMI = Convert.ToSingle(_dtSeletedItem.Rows[0]["TotalCMI"].ToString());
                                        chkCTPL.Checked = true;
                                    }
                                    else
                                    {
                                        chkCTPL.Checked = false;
                                    }
                                }

                                txtCTPL.Text = _totalCMI.ToString("#,000.00");
                                txtGrossPremium_TextChanged(null, null);
                            }
                        }
                    }
                }

                #endregion
            }
            else
            {
                divCompletedQuoteDetails.Visible = false;
            }

            #region Show Customer and Car Details
            MyDatabase _db = new MyDatabase();
            //Customer Details
            string _strSelect = "select P.FirstName, P.SurName, P.DOB, P.Gender, C.Email, C.Mobile, O.TH Occupation, P.Info1, C.OtherContact1, u.ModifiedDate, ISNULL(u.FacebookID, '') FacebookID, ISNULL(p.IsAcceptTC, '') IsAcceptTC "
                                + "from tblCEUsrProfile P INNER JOIN tblOccupationInfo O ON P.Occupation = O.OccupationId "
                                + "INNER JOIN tblCEContact C ON C.RefCEUserID = P.RefCEUserID INNER JOIN tblCEUser u ON u.CEID = C.RefCEUserID "
                                + "Where P.RefCEUserId = " + txtCustomerId.Text;
            DataTable _dtSelect = new DataTable("dtSelect");
            _dtSelect = _db.GetDataTable(_strSelect);
            if (_dtSelect != null && _dtSelect.Rows.Count > 0)
            {
                lblName.Text = _dtSelect.Rows[0]["FirstName"].ToString();
                lblLastName.Text = _dtSelect.Rows[0]["SurName"].ToString();
                lblGender.Text = _dtSelect.Rows[0]["Gender"].ToString() == "M" ? "ชาย" : "หญิง";
                lblDOB.Text = Convert.ToDateTime(_dtSelect.Rows[0]["DOB"].ToString()).ToString("dd/MMM/yyyy");
                lblOccupation.Text = _dtSelect.Rows[0]["Occupation"].ToString();
                lblMobileNo.Text = _dtSelect.Rows[0]["Mobile"].ToString();
                lblRefMobile.Text = lblMobileNo.Text;
                lblEmailAddress.Text = _dtSelect.Rows[0]["Email"].ToString();
                txtConfirmEmail.Text = lblEmailAddress.Text;
                txtOnlineConfirmEmail.Text = lblEmailAddress.Text;
                txtCustomerDetailRemark.Text = _dtSelect.Rows[0]["OtherContact1"].ToString();

                if (_dtSelect.Rows[0]["FacebookID"].ToString() != "" && _dtSelect.Rows[0]["IsAcceptTC"].ToString() == "True")
                {
                    imgFB.Visible = true;
                }

                // 1
                lblUserModifiedDateTime.Text = Convert.ToDateTime(_dtSelect.Rows[0]["ModifiedDate"].ToString()).ToString("dd/MMM/yyyy hh:mm tt");

                txtConfirmEmail.Enabled = true;
                btnSendQuotation.Enabled = true;

                lblRefEmail.Text = lblEmailAddress.Text;
            }

            if (txtConfirmEmail.Text.Contains("@old.com"))
            {
                object oldEmail = _db.ExecuteScalarSqlStatement("Select TOP 1 Email from tblCXBrokerPremiumQuotationEmail WHERE CustomerID = " + txtCustomerId.Text + " AND SendType = 1 ORDER BY ModifiedDate DESC ");
                if (oldEmail != null) txtConfirmEmail.Text = oldEmail.ToString();
            }

            _dtSelect = null;
            _dtSelect = new DataTable("dtSelect");
            bool _IsClaim = false;
            bool _IsAddDriver = false;
            string _vehicleType;
            DateTime _dtCoverCommDate = dateTimeNow;

            _strSelect = "SELECT CP.InsuranceType, CP.GarageType, CP.VehicleType, CP.SumInsured, CP.NCDPercent, CP.IsClaimLastYear, CP.IsCTPL,"
                + " CP.IsAddDriver, CP.NoOfDriver,  CP.CoverageCommenceDate, CP.Info6, CP.Info7, CP.ModifiedDate, CD.Info3, CP.Info8, CP.ProvinceRegistration, "
                + " CP.Deductible, CP.AddAccModAmount, CD.Info1, CP.IsClaimLastYear, CD.Dinfo2, CD.Ninfo5, CP.ModifiedDate "
                + " FROM tblCarPolicy CP INNER JOIN tblCarDetailTH CD ON CD.CarId = CP.CECarId "
                + " WHERE CP.RefCEUserId = " + CustomerID.ToString() + " AND CP.CECarId= " + CarID.ToString();
            _dtSelect = _db.GetDataTable(_strSelect);

            if (_dtSelect != null && _dtSelect.Rows.Count > 0)
            {

                DataRow _drCarPolicy = _dtSelect.Rows[0];
                DataRow _drCarDetail = null;

                // 2. if has
                lblUserModifiedDateTime.Text = Convert.ToDateTime(_dtSelect.Rows[0]["ModifiedDate"].ToString()).ToString("dd/MMM/yyyy hh:mm tt");

                lblInsuranceType.Text = "";
                if (_dtSelect.Rows[0]["InsuranceType"].ToString().Length >= 2)
                {
                    string _strInsType = _dtSelect.Rows[0]["InsuranceType"].ToString().Substring(0, 2);
                    if (_strInsType == "10")
                    {
                        lblInsuranceType.Text = "1";
                    }
                    else if (_strInsType == "11")
                    {
                        lblInsuranceType.Text = "1+";
                    }
                    else if (_strInsType == "20")
                    {
                        lblInsuranceType.Text = "2";
                    }
                    else if (_strInsType == "21")
                    {
                        lblInsuranceType.Text = "2+";
                    }
                    else if (_strInsType == "30")
                    {
                        lblInsuranceType.Text = "3";
                    }
                    else if (_strInsType == "31")
                    {
                        lblInsuranceType.Text = "3+";
                    }
                }
                else
                {
                    lblInsuranceType.Text = "1";
                }

                if (_dtSelect.Rows[0]["Info8"] != DBNull.Value && _dtSelect.Rows[0]["Info8"].ToString().ToUpper().Contains("TESCO200"))
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "JS_ClosedCallAlert", "alert('" + _dtSelect.Rows[0]["Info8"].ToString() + "');", true);
                    lblTESCO200.Text = _dtSelect.Rows[0]["Info8"].ToString();
                    lblTESCO200Two.Text = _dtSelect.Rows[0]["Info8"].ToString();
                }
                if (_dtSelect.Rows[0]["Info8"] != DBNull.Value && _dtSelect.Rows[0]["Info8"].ToString().ToUpper().Contains("Claim"))
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "JS_ClosedCallAlert", "alert('" + _dtSelect.Rows[0]["Info8"].ToString() + "');", true);
                    lblTESCO200.Text = _dtSelect.Rows[0]["Info8"].ToString();
                    lblTESCO200Two.Text = _dtSelect.Rows[0]["Info8"].ToString();
                }
                //Checking Last Year Application Summary
                if (_dtSelect.Rows[0]["Info6"] != DBNull.Value && _dtSelect.Rows[0]["Info6"].ToString() != string.Empty
                    && _dtSelect.Rows[0]["Info7"] != DBNull.Value && _dtSelect.Rows[0]["Info7"].ToString() != string.Empty)
                {
                    _paraList = new SortedList();
                    _paraList.Add("@CECarID", _dtSelect.Rows[0]["Info6"].ToString());
                    _paraList.Add("@CustomerID", CustomerID);
                    _dtApp = new DataTable("tblApp");
                    _dtApp = _db.GetDataTableBySP("sprocCXCRMNonGGApplicationStatusSelectItem", _paraList);
                    if (_dtApp != null && _dtApp.Rows.Count > 0)
                    {
                        if (_dtApp.Rows[0]["Completed"].ToString() == "1")
                        {
                            BrokerPremium _brokerPremium = new BrokerPremium();
                            BrokerPremiumDB _brokerPremiumDB = new BrokerPremiumDB();
                            _brokerPremium = _brokerPremiumDB.GetBrokerPremiumSelectedItem(Convert.ToInt64(_dtSelect.Rows[0]["Info6"].ToString()), CustomerID);
                            lblRenewalStaus.Text = "2";

                            if (_brokerPremium != null && _brokerPremium.CXBrokerPremiumId > 0)
                            {
                                ShowBrokerPremiumDetail(_brokerPremium, true);
                                txtPremiumId.Text = "0";
                            }

                            lblLastYearRefNo.Text = _dtSelect.Rows[0]["Info7"].ToString();
                            lblRenewalStatusMessage.Text = " - Renewal - Last Year Ref.No: " + _dtSelect.Rows[0]["Info7"].ToString();
                            lblCallTypeDesc.Text += " - Renewal";

                            hplReRunQuote.Visible = false;
                            hplNewQuote.Visible = false;
                            btnRenewalQuote.Visible = true;
                            divLinks.Visible = true;
                            divCarDetailList.Visible = false;
                            txtEditLicensePlate.Text = _dtApp.Rows[0]["CarPlate"].ToString();
                            lblEditLicensePlate.Text = txtEditLicensePlate.Text;

                            //Yui@5/2/2015
                            //btnUpDateCar.Visible = false;
                        }
                    }
                }

                lblGarageType.Text = _dtSelect.Rows[0]["GarageType"].ToString() == "1" ? Resources.CarInsurance.Garage_Authorized : Resources.CarInsurance.Garage_Dealer;
                ddlQueryGarageType.Text = _dtSelect.Rows[0]["GarageType"].ToString();

                _vehicleType = _dtSelect.Rows[0]["Info3"].ToString();
                switch (_vehicleType)
                {
                    case "110":
                        lblVehicleType.Text = Resources.CarInsurance.VehicleType_Private;
                        break;
                    case "120":
                        lblVehicleType.Text = Resources.CarInsurance.VehicleType_Commercial;
                        break;
                    case "320":
                        lblVehicleType.Text = Resources.CarInsurance.VehicleType_Pickup;
                        break;
                    default:
                        lblVehicleType.Text = Resources.CarInsurance.VehicleType_Private;
                        break;
                }

                string _strQuoteDate = _dtSelect.Rows[0]["ModifiedDate"].ToString();
                DateTime _dtQuoteDate = dateTimeNow;
                DateTime _dtCompareQuoteDate = dateTimeNow.AddMonths(-1);
                if (DateTime.TryParse(_strQuoteDate, out _dtQuoteDate))
                {
                    lblRefModifiedDateTime.Text = _dtQuoteDate.ToString("dd/MMM/yyyy hh:mm tt");
                    if (DateTime.Compare(_dtCompareQuoteDate, _dtQuoteDate) > 0)
                    {
                        lblQuoteDateTimeStatus.Text = "0";
                        lblQuoteDateTimeStatusMessage.Text = Resources.General.QuoteDateTimeOVER;
                        lblQuoteDateTimeStatusMessage.Font.Bold = true;
                        lblQuoteDateTimeStatusMessage.ForeColor = System.Drawing.Color.Red;
                    }
                    else
                    {
                        lblQuoteDateTimeStatus.Text = "1";
                        lblQuoteDateTimeStatusMessage.Text = Resources.General.QuoteDateTimeOK;
                        lblQuoteDateTimeStatusMessage.Font.Bold = true;
                        lblQuoteDateTimeStatusMessage.ForeColor = System.Drawing.Color.Green;
                    }
                }
                else
                {
                    lblQuoteDateTimeStatus.Text = "0";
                    lblQuoteDateTimeStatusMessage.Text = Resources.General.QuoteDateTimeNOTVALID;
                    lblQuoteDateTimeStatusMessage.Font.Bold = true;
                    lblQuoteDateTimeStatusMessage.ForeColor = System.Drawing.Color.Red;
                }

                lblSumInsured.Text = Convert.ToInt32(_dtSelect.Rows[0]["SumInsured"]).ToString("#,000");

                txtOwnDamage.Text = lblSumInsured.Text;

                lblNCD.Text = _dtSelect.Rows[0]["NCDPercent"].ToString() == "-1" ? "0" : _dtSelect.Rows[0]["NCDPercent"].ToString() + "%";
                ddlEditNCB.Text = _dtSelect.Rows[0]["NCDPercent"].ToString() == "-1" ? "0" : _dtSelect.Rows[0]["NCDPercent"].ToString();

                if (_dtSelect.Rows[0]["Ninfo5"] != DBNull.Value && _dtSelect.Rows[0]["Ninfo5"].ToString() != string.Empty)
                {
                    ddlHowUKnowUs.SelectedIndex = ddlHowUKnowUs.Items.IndexOf(ddlHowUKnowUs.Items.FindByValue(_dtSelect.Rows[0]["Ninfo5"].ToString()));
                }

                lblCTPL.Text = Convert.ToBoolean(_dtSelect.Rows[0]["IsCTPL"]) == true ? "ใช่" : "ไม่ต้องการ";
                _IsClaim = Convert.ToBoolean(_dtSelect.Rows[0]["IsClaimLastYear"].ToString());
                _IsAddDriver = Convert.ToBoolean(_dtSelect.Rows[0]["IsAddDriver"].ToString());

                // For Renew Ext Com Date
                LoadExtComDate();
                //***********************

                string _coverCommDate = _dtSelect.Rows[0]["CoverageCommenceDate"].ToString();

                if (DateTime.TryParse(_coverCommDate, out _dtCoverCommDate))
                {
                    lblCoverCommencementDate.Text = _dtCoverCommDate.ToString("dd/MMM/yyyy");
                    if (DateTime.Compare(dateTimeNow, _dtCoverCommDate) > 0)
                    {
                        lblCommenceDateStatus.Text = "0";
                        lblCommenceDateStatusMessage.Text = Resources.General.CommencementOVER;
                        lblCommenceDateStatusMessage.Font.Bold = true;
                        lblCommenceDateStatusMessage.ForeColor = System.Drawing.Color.Red;

                        ListItem myItem = new ListItem(lblCoverCommencementDate.Text, lblCoverCommencementDate.Text);

                        ddlEditCoverCommencementDate.Items.Insert(0, myItem);
                        ddlEditCoverCommencementDate.Items[0].Attributes.Add("style", "color:red;");

                        lblEditCoverCommencementDateCaption.Font.Bold = true;
                        lblEditCoverCommencementDateCaption.ForeColor = System.Drawing.Color.Red;
                        ClientScript.RegisterStartupScript(this.GetType(), "JS_ClosedCallAlert", "alert('" + Resources.General.CommencementCheck + "');", true);
                        lblEditCoverCommencementDateMessage.Text = Resources.General.CommencementCheck;
                    }
                    else
                    {
                        lblCommenceDateStatus.Text = "1";
                        lblCommenceDateStatusMessage.Text = Resources.General.CommencementOK;
                        lblCommenceDateStatusMessage.Font.Bold = true;
                        lblCommenceDateStatusMessage.ForeColor = System.Drawing.Color.Green;
                    }

                    ddlEditCoverCommencementDate.Text = lblCoverCommencementDate.Text;
                    lblEditCoverCommencementDate.Text = lblCoverCommencementDate.Text;

                    // For Renew Ext Com Date
                    if (_dtSelect.Rows[0]["Dinfo2"] != DBNull.Value)
                    {
                        chkExtComDate.Checked = true;
                        ddlExtComDate.Style.Add("visibility", "visible");
                        ddlExtComDate.SelectedIndex = ddlExtComDate.Items.IndexOf(ddlExtComDate.Items.FindByValue(Convert.ToDateTime(_dtSelect.Rows[0]["Dinfo2"]).ToString("yyyy-MM-dd")));

                        if (ddlExtComDate.SelectedIndex == -1)
                            ddlExtComDate.Items.Insert(1, new ListItem(Convert.ToDateTime(_dtSelect.Rows[0]["Dinfo2"]).ToString("dd/MMM/yyyy"), Convert.ToDateTime(_dtSelect.Rows[0]["Dinfo2"]).ToString("yyyy-MM-dd")));
                    }
                }
                else
                {
                    lblCommenceDateStatus.Text = "0";
                    lblCommenceDateStatusMessage.Text = Resources.General.CommencementNOTVALID;
                    lblCommenceDateStatusMessage.Font.Bold = true;
                    lblCommenceDateStatusMessage.ForeColor = System.Drawing.Color.Red;
                }

                CheckQuoteStatus();

                if (_IsAddDriver == true)
                {
                    lblDriverCount.Text = _dtSelect.Rows[0]["NoOfDriver"].ToString();
                    ddlEditNamedDriver.Text = lblDriverCount.Text;
                    chkNamedDriver.Checked = true;
                }
                else
                {
                    lblDriverCount.Text = "0";
                    ddlEditNamedDriver.Text = "0";
                    chkNamedDriver.Checked = false;
                }

                lblClaimInfo.Text = _IsClaim == true ? "ใช่" : "ไม่มี";

                _dtSelect = null;
                _dtSelect = new DataTable("dtSelect");

                _strSelect = " Select CD.MakeModelDesc, CD.ManufactYear, CD.Info15, CD.Info16, CD.Info17, CD.Info18, CD.Info19, P.TH CurrentInsurer, "
                            + " CD.BInfo1, CD.CarMake, CD.CarModel, CD.Body, CD.CC, CD.Door, CD.Info1, CD.Ninfo5 "
                            + " from tblCarDetailTH CD"
                            + " INNER JOIN tblPreInsurer P ON CAST(CD.Info1 AS INT) = P.PreInsurerId"
                            + " Where P.CompanyType = 1 And P.ServiceType = 100 AND CD.RefCEUserId = " + txtCustomerId.Text + " And CD.CarId= " + txtCarId.Text;
                _dtSelect = _db.GetDataTable(_strSelect);
                if (_dtSelect != null && _dtSelect.Rows.Count > 0)
                {
                    _drCarDetail = _dtSelect.Rows[0];


                    lblCarMakeModel.Text = _dtSelect.Rows[0]["MakeModelDesc"].ToString();
                    lblRegYear.Text = _dtSelect.Rows[0]["ManufactYear"].ToString();
                    lblCurrentInsurer.Text = _dtSelect.Rows[0]["CurrentInsurer"].ToString();

                    if (btnRenewalQuote.Visible == false || lblRenewalStaus.Text == "2")
                    {
                        divEditDetail.Visible = true;

                        if (_dtSelect.Rows[0]["Info15"] != DBNull.Value && _dtSelect.Rows[0]["Info15"].ToString() != string.Empty)
                        {
                            txtEditLicensePlate.Text = _dtSelect.Rows[0]["Info15"].ToString();
                            lblEditLicensePlate.Text = _dtSelect.Rows[0]["Info15"].ToString();
                        }

                        if (_dtSelect.Rows[0]["Info16"] != DBNull.Value && _dtSelect.Rows[0]["Info16"].ToString() != string.Empty)
                        {
                            ddlEditNCB.Text = _dtSelect.Rows[0]["Info16"].ToString();
                        }

                        if (_dtSelect.Rows[0]["Info17"] != DBNull.Value && _dtSelect.Rows[0]["Info17"].ToString() != string.Empty)
                        {
                            ddlEditNamedDriver.Text = _dtSelect.Rows[0]["Info17"].ToString();
                        }

                        if (_dtSelect.Rows[0]["Info19"] != DBNull.Value && _dtSelect.Rows[0]["Info19"].ToString() != string.Empty)
                        {
                            ddlEditCoverCommencementDate.Text = _dtSelect.Rows[0]["Info19"].ToString();
                            lblEditCoverCommencementDate.Text = _dtSelect.Rows[0]["Info19"].ToString();
                        }

                        if (_dtSelect.Rows[0]["Ninfo5"] != DBNull.Value && _dtSelect.Rows[0]["Ninfo5"].ToString() != string.Empty)
                        {
                            ddlHowUKnowUs.SelectedIndex = ddlHowUKnowUs.Items.IndexOf(ddlHowUKnowUs.Items.FindByValue(_dtSelect.Rows[0]["Ninfo5"].ToString()));
                        }
                    }
                    else
                    {
                        divEditDetail.Visible = false;
                    }
                }

                divCustomerPolicyDetail.Visible = true;

                SetKawna(_drCarPolicy, _drCarDetail);
            }

            _dtSelect = null;
            _dtSelect = new DataTable("dtSelect");

            _db = null;
            _dtSelect = null;
            #endregion

            #region Show Hide Links
            if (divCompletedQuoteDetails.Visible == false && btnRenewalQuote.Visible == false)
            {
                hplNewQuote.NavigateUrl = "callme-newlead-quotes.aspx?leadid=" + lblAgentLeadID.Text + "&callmeid=" + txtCallMeId.Text + "&calltype=" + lblCallType.Text + "&carid=0" + "&custid=" + txtCustomerId.Text;
                hplReRunQuote.NavigateUrl = "callme-newlead-quotes.aspx?leadid=" + lblAgentLeadID.Text + "&callmeid=" + txtCallMeId.Text + "&calltype=" + lblCallType.Text + "&carid=" + txtCarId.Text + "&custid=" + txtCustomerId.Text;

                hplNewQuote.Visible = true;
                hplReRunQuote.Visible = true;
                btnRenewalQuote.Visible = false;

                divEditDetail.Visible = true;
                divPremiumList.Visible = true;

                divResultExcel.Visible = true;
                divLinks.Visible = true;
                divCallHistory.Visible = true;

                //Yui@5/2/2015
                //btnUpDateCar.Visible = true;

                //chkIsPromotion.Checked = false;
                //chkIsPromotion.Enabled = false;
            }
            else
            {
                divLinks.Visible = true;
                // Renewal show
                if (Session[General.IsRenewalAgent].ToString() == "1")
                {
                    btnRenewalQuote.Visible = true;
                    hplNewQuote.Visible = false;
                    hplReRunQuote.Visible = false;
                    RenewPDF();
                    //chkIsPromotion.Checked = true;
                    //chkIsPromotion.Enabled = true;
                }
                else
                {
                    btnRenewalQuote.Visible = false;

                    hplNewQuote.NavigateUrl = "callme-newlead-quotes.aspx?leadid=" + lblAgentLeadID.Text + "&callmeid=" + txtCallMeId.Text + "&calltype=" + lblCallType.Text + "&carid=0" + "&custid=" + txtCustomerId.Text;
                    hplNewQuote.Visible = true;
                    hplReRunQuote.NavigateUrl = "callme-newlead-quotes.aspx?leadid=" + lblAgentLeadID.Text + "&callmeid=" + txtCallMeId.Text + "&calltype=" + lblCallType.Text + "&carid=" + txtCarId.Text + "&custid=" + txtCustomerId.Text;
                    hplReRunQuote.Visible = true;

                    //chkIsPromotion.Checked = false;
                    //chkIsPromotion.Enabled = false;
                }

                divEditDetail.Visible = true;
                divPremiumList.Visible = true;
                divCallHistory.Visible = true;

                //Yui@5/2/2015
                divResultExcel.Visible = true;
                //divResultExcel.Visible = false;
                //gvCarResultExcel.DataSource = null;
                //gvCarResultExcel.DataBind();
                //divSendQuotes.Visible = false;
                //btnUpDateCar.Visible = false;
            }
            #endregion

            #region Broker Premium
            grvPremiumList.DataBind();
            if (grvPremiumList.Rows.Count > 0)
            {
                string url = "PremiumDownload.aspx?carid=" + txtCarId.Text.ToString();// +"," + txtVehicleNumber.Text.ToString();
                hplPremiumDownLoad.NavigateUrl = url;
            }
            else
            {
                hplPremiumDownLoad.Visible = false;
                hplPremiumDownLoad.NavigateUrl = "";
            }

            divCXBrokerPremium.Visible = true;
            #endregion

            #region Call Status
            if (divCustomerPolicyDetail.Visible)
            {
                divCXBrokerPremium.Visible = true;
                ddlCICallStatus.Enabled = true;
                divCallStatus.Visible = true;

                txtCallBackCount.Text = GetCallBackCount();

                CallStatus CI_callstatus = new CallStatus();
                CallStatusDB CI_callstatusdb = new CallStatusDB();
                CI_callstatus = CI_callstatusdb.GetCallStatus(Convert.ToInt64(lblAgentLeadID.Text), Convert.ToInt32(lblCallType.Text));

                if (CI_callstatus != null)
                {
                    txtCXCRMId.Text = CI_callstatus.CXCRMId.ToString();

                    txtCallBackDateTime.Text = "0";

                    rdoCallFinish.Checked = false;
                    rdoCallBack.Checked = false;

                    lblCallSessionName.Text = "<table class='sTable'>";

                    if (CI_callstatus.CallFinishType == 1)
                    {
                        rdoCallFinish.Checked = true;

                        ClientScript.RegisterStartupScript(this.GetType(), "JS_ClosedCallAlert", "alert('" + Resources.General.LastCallStatus.ToUpper() + " : " + lblCallTypeDesc.Text + " - " + Resources.General.CLOSEDCALL + lblRenewalStatusMessage.Text + "');", true);

                        if (CI_callstatus.CallStatusTypeID == 10)
                        {
                            //&& CI_callstatus.MainCallStatusTypeID == 7
                            txtCallBackDateTime.Text = CI_callstatus.CallBackDateTime.ToString("dd/MMM/yyyy hh:mm tt");
                            DateTime _dtTargetDateTime = dateTimeNow;
                            if (DateTime.TryParse(txtCallBackDateTime.Text, out _dtTargetDateTime))
                            {
                                txtTargetDate.Text = _dtTargetDateTime.ToString("dd-MMM-yyyy");
                                ddlTHour.SelectedIndex = ddlTHour.Items.IndexOf(ddlTHour.Items.FindByValue(_dtTargetDateTime.ToString("HH")));
                                ddlTMin.Text = "00";

                                lblCallSessionName.Text += "<tr><td><b style='color:red;'>" + Resources.General.CLOSEDCALL + " >> " + Resources.CarInsurance.NewCommencementDate + ":</b></td><td>" + CI_callstatus.CallBackDateTime.ToString("dd/MMM/yyyy") + "</td>";
                            }
                            else
                            {
                                txtCallBackDateTime.Text = "0";
                            }
                        }
                        else
                        {
                            lblCallSessionName.Text += "<tr><td><b style='color:red;'>" + Resources.General.CLOSEDCALL + "</b></td>";
                        }
                    }
                    else if (CI_callstatus.CallFinishType == 2)
                    {
                        rdoCallBack.Checked = true;
                        ddlCBAgentList.Text = CI_callstatus.CallBackAgentID.ToString();
                        txtCallBackDateTime.Text = CI_callstatus.CallBackDateTime.ToString("dd/MMM/yyyy hh:mm tt");
                        lblCallSessionName.Text += "<tr><td><b style='color:red;'>" + Resources.General.Callback.ToUpper() + "</b></td><td>" + txtCallBackDateTime.Text + "</td>";
                        ClientScript.RegisterStartupScript(this.GetType(), "JS_CallBackCallAlert", "alert('" + Resources.General.LastCallStatus.ToUpper() + " : " + lblCallTypeDesc.Text + " - " + Resources.General.Callback + lblRenewalStatusMessage.Text + " [" + txtCallBackDateTime.Text + "]');", true);
                        DateTime _dtTargetDateTime = dateTimeNow;
                        if (DateTime.TryParse(txtCallBackDateTime.Text, out _dtTargetDateTime))
                        {
                            txtTargetDate.Text = _dtTargetDateTime.ToString("dd-MMM-yyyy");
                            ddlTHour.SelectedIndex = ddlTHour.Items.IndexOf(ddlTHour.Items.FindByValue(_dtTargetDateTime.ToString("HH")));
                            ddlTMin.Text = "00";
                        }
                        else
                        {
                            txtCallBackDateTime.Text = "0";
                        }
                    }
                    else if (CI_callstatus.CallFinishType == 3)
                    {

                        lblCallSessionName.Text += "<tr><td><b style='color:blue;'>" + Resources.General.FollowUp.ToUpper() + "</b></td>";
                        ClientScript.RegisterStartupScript(this.GetType(), "JS_FollowUpCallAlert", "alert('" + Resources.General.LastCallStatus.ToUpper() + " : " + lblCallTypeDesc.Text + " - " + Resources.General.FollowUp.ToUpper() + lblRenewalStatusMessage.Text + "');", true);
                    }

                    rdoCallFinish_CheckedChanged(null, null);
                    if (ddlCIMainCallStatus.Items.Count > 0)
                    {
                        ddlCIMainCallStatus.Text = CI_callstatus.MainCallStatusTypeID.ToString();
                        ddlCIMainCallStatus_SelectedIndexChanged(null, null);

                        if (ddlCICallStatus.Items.Count > 0)
                        {
                            ddlCICallStatus.Text = CI_callstatus.CallStatusTypeID.ToString();
                            ddlCICallStatus_SelectedIndexChanged(null, null);
                        }
                    }

                    txtCallStatus.Text = Server.HtmlDecode(CI_callstatus.Remark);
                    lblLastCallStatusMessage.Text = Resources.General.FOUND + " [" + Resources.General.LastDateTime + ": " + CI_callstatus.ModifiedDate.ToString("dd/MMM/yyyy hh:mm tt") + "]";
                }
                else
                {
                    lblLastCallStatusMessage.Text = Resources.General.NEW;
                    lblCallSessionName.Text = Resources.General.NEWCALLPENDING;
                    ClientScript.RegisterStartupScript(this.GetType(), "JS_NewCallPendingAlert", "alert('" + lblCallTypeDesc.Text + " - " + Resources.General.NEWCALLPENDING + lblRenewalStatusMessage.Text + "');", true);
                }

                CI_callstatus = null;
                CI_callstatusdb = null;
            }
            #endregion

            #region Call History
            lblCallHistoryFoundCount.Text = "0";
            gvCallHistory.DataBind();
            //GetCallHistory();
            if (lblCallHistoryFoundCount.Text != "0")
            {
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + lblCallHistoryMessage.Text + "');", true);
            }
            #endregion

            // 19/3/2014
            //CheckApplicationStatus();
        }
    }

    protected void btnRenewQuote_Click(object sender, EventArgs e)
    {
        try
        {
            if (lblRenewalStaus.Text == "2" && Convert.ToInt32(lblCarMoreDetailID.Text) > 0)
            {
                btnSubmitPremium.Enabled = false;
                btnNewPremium.Enabled = false;
                btnEditSubmit.Enabled = false;
                lblPremiumMessage.Text = Resources.General.NonGGFoundAppDetailSubmission;
                lblPremiumMessage.ForeColor = System.Drawing.Color.Red;
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.NonGGFoundAppDetailSubmission + "');", true);
                return;
            }

            Int64 _agentLeadId = 0;

            if (!Int64.TryParse(lblAgentLeadID.Text, out _agentLeadId))
            {
                _agentLeadId = 0;
            }

            Int64 _customerId = 0;

            if (!Int64.TryParse(txtCustomerId.Text, out _customerId))
            {
                _customerId = 0;
            }

            Int64 _carId = 0;
            Int64 _outCarID = 0;

            if (!Int64.TryParse(txtCarId.Text, out _carId))
            {
                _carId = 0;
            }

            Int64 _callMeId = 0;
            Int64 _agentID = 0;

            if (!Int64.TryParse(txtAgentId.Text, out _agentID))
            {
                _agentID = 0;
            }

            LoadCallMeAgentLeads(_agentLeadId, _customerId, _carId, Convert.ToInt64(Session[CE.Global.General.UserId].ToString()), Convert.ToInt32(lblCallType.Text), _callMeId, out _agentLeadId, out _customerId, out _outCarID);

            if (_agentLeadId > 0)
            {
                string _strParameters = "leadid=" + _agentLeadId.ToString() + "&calltype=" + lblCallType.Text;
                _strParameters += "&custid=" + _customerId.ToString() + "&carid=" + _outCarID.ToString();

                if (_carId == _outCarID)
                {
                    if (lblRenewalStaus.Text == "1")
                    {
                        _strParameters += "&renew=1";
                    }
                    else if (lblRenewalStaus.Text == "2")
                    {
                        _strParameters += "&renew=2";
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    _strParameters += "&renew=2";
                }

                _strParameters += "&refno=" + lblLastYearRefNo.Text;

                if (_customerId > 0 && _carId > 0)
                {
                    if (lblRenewalStaus.Text == "1")
                    {
                        if (_carId == _outCarID)
                        {
                            Response.Redirect("~/carinsurance/offline/callme-newlead-quotes.aspx?" + _strParameters.ToString());
                        }
                        else
                        {
                            if (CheckCXBrokerPremiumCount(_outCarID, _customerId))
                            {
                                Response.Redirect("~/carinsurance/offline/ViewCINoMatchFound.aspx?" + _strParameters.ToString());
                            }
                            else
                            {
                                Response.Redirect("~/carinsurance/offline/callme-newlead-quotes.aspx?" + _strParameters.ToString());
                            }
                        }
                    }
                    else
                    {
                        Response.Redirect("~/carinsurance/offline/callme-newlead-quotes.aspx?" + _strParameters.ToString());
                    }
                }
                else
                {
                    lblRenewalQuoteMessage.Text = "Please try again later.";
                    lblRenewalQuoteMessage.Font.Bold = true;
                    lblRenewalQuoteMessage.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
        catch (Exception Ex)
        {
            lblRenewalQuoteMessage.Text = Ex.Message;
            lblRenewalQuoteMessage.Font.Bold = true;
            lblRenewalQuoteMessage.ForeColor = System.Drawing.Color.Red;
        }
    }

    public bool CheckCXBrokerPremiumCount(Int64 CarID, Int64 CustomerID)
    {
        bool _Result = false;
        MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
        SortedList _sPara = new SortedList();
        string _spName = "[sprocCXBrokerPremiumGetCount]";
        _sPara.Add("@CarID", CarID);
        _sPara.Add("@CustomerID", CustomerID);
        _sPara.Add("@ProductType", "CIN");

        object _objCount = _db.ExecuteScalarSP(_spName, _sPara);
        if (_objCount != null && Convert.ToInt32(_objCount) > 0)
        {
            _Result = true;
        }

        return _Result;
    }

    private void LoadCallMeAgentLeads(Int64 AgentLeadId, Int64 CustomerID, Int64 CarId, Int64 AgentId, Int32 CallTypeId, Int64 CallMeId, out Int64 outAgentLeadID, out Int64 outCustomerID, out Int64 outCarID)
    {
        string _spName = "sprocCXCRMAgentLeadDetailsSelectSingleItem";
        MyDatabase _db = new MyDatabase();
        DataTable _dtCallMeAgentLeads = new DataTable("tblCallMeAgentLeads");
        SortedList _paraList = new SortedList();
        _paraList.Add("@AgentLeadId", AgentLeadId);
        _paraList.Add("@CustomerID", CustomerID);
        _paraList.Add("@CarID", CarId);
        _paraList.Add("@AgentId", AgentId);
        _paraList.Add("@CallTypeId", CallTypeId);
        _paraList.Add("@CallMeId", CallMeId);
        _dtCallMeAgentLeads = _db.GetDataTableBySP(_spName, _paraList);

        outAgentLeadID = 0;
        outCustomerID = 0;
        outCarID = 0;
        if (_dtCallMeAgentLeads != null && _dtCallMeAgentLeads.Rows.Count > 0)
        {
            lblAgentLeadID.Text = _dtCallMeAgentLeads.Rows[0]["AgentLeadId"].ToString();
            txtCustomerId.Text = _dtCallMeAgentLeads.Rows[0]["CustomerId"].ToString();
            txtCarId.Text = _dtCallMeAgentLeads.Rows[0]["CarId"].ToString();
            txtCallMeId.Text = _dtCallMeAgentLeads.Rows[0]["CallMeId"].ToString();
            lblCallType.Text = _dtCallMeAgentLeads.Rows[0]["CallType"].ToString();

            outAgentLeadID = Convert.ToInt64(lblAgentLeadID.Text);
            outCustomerID = Convert.ToInt64(txtCustomerId.Text);
            outCarID = Convert.ToInt64(txtCarId.Text);
        }

    }

    private void ResetCallStatus()
    {
        rdoCallFinish.Checked = true;

        rdoCallBack.Checked = false;
        rdoCallFinish_CheckedChanged(null, null);
        ddlCIMainCallStatus.SelectedIndex = 0;
        ddlCIMainCallStatus_SelectedIndexChanged(null, null);
        txtCallStatus.Text = string.Empty;
        txtCallStatusId.Text = "-1";
        txtCXCRMId.Text = "0";
    }

    protected void ddlCIMainCallStatus_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCIMainCallStatus.Items.Count > 0 && ddlCIMainCallStatus.SelectedIndex >= 0)
        {
            LoadCallStatusList(Convert.ToInt32(ddlCIMainCallStatus.Text));
        }
    }

    protected void ddlCICallStatus_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCICallStatus.Text == "10")
        {
            //ddlCIMainCallStatus.Text == "7" && 
            //lblCallBackDateTime.Text = Resources.CarInsurance.NewCommencementDate;
            //txtTargetDate.Text = dateTimeNow.ToString("dd-MMM-yyyy");
            //cexTargetDate.StartDate = dateTimeNow;
            //cexTargetDate.EndDate = dateTimeNow.AddDays(180);
            //trCallBack1.Visible = true;
            //spanTimeDrowdown.Visible = false;

            //27Feb2014
            //txtTargetDate.Text = dateTimeNow.AddDays(61).ToString("dd-MMM-yyyy");
            //cexTargetDate.StartDate = dateTimeNow.AddDays(61);
            //11Mar2014
            txtTargetDate.Text = dateTimeNow.AddDays(1).ToString("dd-MMM-yyyy");
            cexTargetDate.StartDate = dateTimeNow.AddDays(1);
            cexTargetDate.EndDate = dateTimeNow.AddDays(180);
            lblCallBackDateTime.Text = Resources.General.DateTime;
            ddlCBAgentList.SelectedIndex = ddlCBAgentList.Items.IndexOf(ddlCBAgentList.Items.FindByValue(Session[General.UserId].ToString()));
            trCallBack1.Visible = true;
            spanTimeDrowdown.Visible = true;
        }
        else
        {
            txtTargetDate.Text = dateTimeNow.ToString("dd-MMM-yyyy");
            cexTargetDate.StartDate = dateTimeNow;
            cexTargetDate.EndDate = GetCallBackDateLimit(15); //dateTimeNow.AddDays(21);
            lblCallBackDateTime.Text = Resources.General.DateTime;
            ddlCBAgentList.SelectedIndex = ddlCBAgentList.Items.IndexOf(ddlCBAgentList.Items.FindByValue(Session[General.UserId].ToString()));
            if (!rdoCallBack.Checked)
            {
                trCallBack1.Visible = false;
                spanTimeDrowdown.Visible = true;
            }
        }
    }

    private void LoadMainCallStatusList(int intType)
    {
        try
        {
            MyDatabase _db = new MyDatabase();
            string _strSQL = "Select MainCallStatusTypeID, " + Resources.DBTable.FieldName + " AS Description from tblCXCRMMainCallStatusType Where [Status] = 1 And [Type] = " + intType.ToString();

            DataTable _dtList = new DataTable("tblList");
            _dtList = _db.GetDataTable(_strSQL);
            ddlCIMainCallStatus.Items.Clear();
            //ddlCIMainCallStatus.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
            if (_dtList != null && _dtList.Rows.Count > 0)
            {
                ddlCIMainCallStatus.DataSource = _dtList;
                ddlCIMainCallStatus.DataTextField = "Description";
                ddlCIMainCallStatus.DataValueField = "MainCallStatusTypeID";
                ddlCIMainCallStatus.DataBind();
                //for (int i = 0; i < _dtList.Rows.Count; i++)
                //{
                //    ddlCIMainCallStatus.Items.Add(new ListItem(_dtList.Rows[i]["Description"].ToString(), _dtList.Rows[i]["MainCallStatusTypeID"].ToString()));
                //}
            }
        }
        catch (Exception Ex)
        {
            lblCallSessionName.Text += "<br/><b style='color:red;'>" + Resources.General.ERROR + "</b>: at LoadMainCallStatusList()<br/>" + Ex.Message + "<br/><br/>" + Ex.StackTrace;
        }
    }

    private void LoadCallStatusList(int MainStatusID)
    {
        try
        {
            MyDatabase _db = new MyDatabase();
            string _strSQL = "Select CallStatusTypeID, " +
                                " '[' + CAST(StatusCode AS VARCHAR) + '] ' + " + Resources.DBTable.FieldName + " AS Description " +
                                " FROM tblCXCRMCallStatusType Where [Status] = 1 And [MainCallStatusTypeID] = " + MainStatusID.ToString();
            DataTable _dtList = new DataTable("tblList");
            _dtList = _db.GetDataTable(_strSQL);
            ddlCICallStatus.Items.Clear();
            if (_dtList != null && _dtList.Rows.Count > 0)
            {
                ddlCICallStatus.DataSource = _dtList;
                ddlCICallStatus.DataTextField = "Description";
                ddlCICallStatus.DataValueField = "CallStatusTypeID";
                ddlCICallStatus.DataBind();
                //for (int i = 0; i < _dtList.Rows.Count; i++)
                //{
                //    ddlCICallStatus.Items.Add(new ListItem(_dtList.Rows[i]["Description"].ToString(), _dtList.Rows[i]["CallStatusTypeID"].ToString()));
                //}
            }
            ddlCICallStatus.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        }
        catch (Exception Ex)
        {
            lblCallSessionName.Text += "<br/><b style='color:red;'>" + Resources.General.ERROR + "</b>: at LoadCallStatusList()<br/>" + Ex.Message + "<br/><br/>" + Ex.StackTrace;
        }
    }

    protected void rdoCallFinish_CheckedChanged(object sender, EventArgs e)
    {
        trCallBack1.Visible = false;
        trCallBack2.Visible = false;
        if (rdoCallNotBuy.Checked)
        {
            LoadMainCallStatusList(4);
        }
        else if (rdoCallFinish.Checked)
        {
            LoadMainCallStatusList(1);
        }
        else if (rdoCallBack.Checked)
        {
            txtTargetDate.Text = dateTimeNow.ToString("dd-MMM-yyyy");
            cexTargetDate.StartDate = dateTimeNow;
            cexTargetDate.EndDate = GetCallBackDateLimit(15); //dateTimeNow.AddDays(21);
            trCallBack1.Visible = true;
            trCallBack2.Visible = true;
            lblCallBackDateTime.Text = Resources.General.DateTime;
            LoadMainCallStatusList(2);
            spanTimeDrowdown.Visible = true;
        }

        if (ddlCIMainCallStatus.Items.Count > 0)
        {
            ddlCIMainCallStatus.SelectedIndex = 0;
            ddlCIMainCallStatus_SelectedIndexChanged(sender, e);
        }
    }

    protected void ddlAgent_SelectedIndexChanged(object sender, EventArgs e)
    {
        btnSubmit_Click(sender, e);
    }

    protected void ddlSubmittedDate_SelectedIndexChanged(object sender, EventArgs e)
    {
        btnSubmit_Click(sender, e);
    }

    protected void ddlVehicleBodyType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlVehicleBodyType.Text == "1")
        {
            txtCTPL.Text = "645.21";
        }
        else if (ddlVehicleBodyType.Text == "2")
        {
            txtCTPL.Text = "967.28";
        }
        else
        {
            txtCTPL.Text = "0";
        }

        txtGrossPremium_TextChanged(sender, e);
    }

    protected void ddlBrokerProvider_SelectedIndexChanged(object sender, EventArgs e)
    {
        //lblPremiumError.Text = "";
        //lblPremiumMessage.Text = "";
        //Yui@26/05/2014 : No Bank Customer
        //LoadBrokerCoverType();

        GetRefNum();
        if (ddlBrokerCoverType.SelectedIndex != 0)
            ddlBrokerCoverType_SelectedIndexChanged(sender, e);
    }

    private void GetRefNum()
    {
        if (txtGG.Text.Trim() != "GGSPECIAL")
        {
            lblQRefNo.Text = CE.Global.General.GetReferenceNumber(txtCarId.Text.Trim(), ddlBrokerProvider.Text.Trim());
        }
        else
        {
            lblQRefNo.Text = CE.Global.General.GetGGReferenceNumber(txtCarId.Text.Trim(), ddlBrokerProvider.Text.Trim());
        }
    }

    protected void ddlBrokerCoverType_SelectedIndexChanged(object sender, EventArgs e)
    {
        //if (ddlBrokerProvider.Text == "43" && (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11") && txtUserTypeId.Text == "1001")
        //{
        //    ddlGarageType.Items.Clear();
        //    ddlGarageType.Items.Insert(0, new ListItem(Resources.CarInsurance.Garage_Authorized, "1"));
        //    ddlGarageType.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        //}
        //else
        //{
        //    ddlGarageType.Items.Clear();
        //    ddlGarageType.Items.Insert(0, new ListItem(Resources.CarInsurance.Garage_Dealer, "2"));
        //    ddlGarageType.Items.Insert(0, new ListItem(Resources.CarInsurance.Garage_Authorized, "1"));
        //    ddlGarageType.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        //}

        if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11")
        {
            chkMile.Enabled = true;
        }
        else
        {
            chkMile.Checked = false;
            chkMile.Enabled = false;
        }

        LoadDiscountPercentageList();
        LoadMonthlyInstallment();
        LoadBrokerDefault(); //Sop Create method and updated on 16 Nov 2012 from BKK

    }

    protected void ddlTesco_SelectedIndexChanged(object sender, EventArgs e)
    {
        lblTesco.Text = "";

        if (ddlTesco.Text == "2")
        {
            decimal _tesco = 0;
            if (txtTescoAmount.Text != string.Empty)
            {
                _tesco = Convert.ToDecimal(txtTescoAmount.Text);
            }
            if (_tesco > 0)
            {
                lblTesco.Text = "(- from Premium)";
            }
            else
            {
                lblTesco.Text = "";
            }
        }
        else
        {
            lblTesco.Text = "";
        }
    }

    protected void grvPremiumList_SelectedIndexChanged(object sender, EventArgs e)
    {
        //lblPremiumError.Text = "";
        //lblPremiumMessage.Text = "";
        BrokerPremium _brokerPremium = new BrokerPremium();
        BrokerPremiumDB _brokerPremiumdb = new BrokerPremiumDB();
        ClearFields();
        if (grvPremiumList.SelectedIndex >= 0)
        {
            DataKey _dKey = grvPremiumList.SelectedDataKey;
            Int64 _premiumId = Convert.ToInt64(_dKey.Values[0]);
            Int64 _brokerId = Convert.ToInt64(_dKey.Values[1]);
            string _QuoteRefNo = _dKey.Values[3].ToString();
            if (_QuoteRefNo.ToString().Trim().Substring(0, 2) == "GG")
            {
                txtGG.Text = "GGSPECIAL";
            }
            else
            {
                if (txtGG.Text == "GGSPECIAL") txtGG.Text = "";
            }

            Int64 _AgentId = 0;
            if (!Int64.TryParse(_dKey.Values[2].ToString(), out _AgentId))
            {
                _AgentId = 0;
            }

            if (Session[General.UserRole] != null && Session[General.UserRole].ToString() != "100")
            {
                ddlAgentbyAdmin.SelectedIndex = ddlAgentbyAdmin.Items.IndexOf(ddlAgentbyAdmin.Items.FindByValue(_AgentId.ToString()));
                //try
                //{
                //    ddlAgentbyAdmin.Text = _AgentId.ToString();
                //}
                //catch (Exception ex)
                //{
                //    ddlAgentbyAdmin.Text = "0";
                //}
            }
            string _ProductType = "CIN";
            Int64 _CECarId = Convert.ToInt64(txtCarId.Text);
            Int64 _CustomerId = Convert.ToInt64(txtCustomerId.Text);

            _brokerPremium = _brokerPremiumdb.GetBrokerPremiumSingleItem(_premiumId, _brokerId, _CECarId, _CustomerId, _ProductType);
            if (_brokerPremium != null)
            {
                if (ddlBrokerProvider.Items.Count == 2)
                {
                    LoadBrokerProvider();
                }
                ShowBrokerPremiumDetail(_brokerPremium, false);
            }
            else
            {
                ClearFields();
            }
        }
        else
        {
            ClearFields();
        }
        _brokerPremium = null;
        _brokerPremiumdb = null;
    }

    private short _discountPercentage = -1;
    private void ShowBrokerPremiumDetail(BrokerPremium _brokerPremium, bool bLoadForRenewal)
    {
        txtPremiumId.Text = _brokerPremium.CXBrokerPremiumId.ToString();
        //if (txtGG.Text.Trim() == "GGSPECIAL")
        //{
        //    DataTable _dtBrokerProvider = General.GetComboItem("BrokerProvider", "CXBrokerProviderId", _brokerPremium.CXBrokerProviderId.ToString(), true);
        //    if (_dtBrokerProvider != null && _dtBrokerProvider.Rows.Count > 0)
        //    {
        //        ddlBrokerProvider.Items.Clear();
        //        ddlBrokerProvider.DataSource = _dtBrokerProvider;
        //        ddlBrokerProvider.DataTextField = _dtBrokerProvider.Columns[0].ColumnName.ToString();
        //        ddlBrokerProvider.DataValueField = _dtBrokerProvider.Columns[1].ColumnName.ToString();
        //        ddlBrokerProvider.DataBind();
        //        ddlBrokerProvider.Items.Insert(0, new ListItem("Select", "-1"));
        //    }
        //}
        ddlBrokerProvider.SelectedIndex = ddlBrokerProvider.Items.IndexOf(ddlBrokerProvider.Items.FindByValue(_brokerPremium.CXBrokerProviderId.ToString()));
        if (txtGG.Text.Trim() == "GGSPECIAL")
            ddlBrokerProvider.Enabled = false;
        else
            ddlBrokerProvider.Enabled = true;
        //ddlBrokerProvider_SelectedIndexChanged(null, null);
        GetRefNum();
        txtNetPremium.Text = _brokerPremium.Premium.ToString();

        //มันอยู่ที่ ddlBrokerCoverType_SelectedIndexChanged แล้วนี่ไมต้องมีที่นี่อีก เอาออก
        //if (txtGG.Text.Trim() == "GGSPECIAL")
        //{
        //    ddlDiscountPercentage.Items.Clear();
        //    ddlDiscountPercentage.Items.Add(new ListItem("18 %", "18"));
        //    ddlDiscountPercentage.Items.Add(new ListItem("0 %", "0"));
        //    ddlDiscountPercentage.Text = "18";
        //}
        //else if (_brokerPremium.DiscountPercentage >= 5 && bLoadForRenewal == false) //Sakthi on 29 Apr 2013 if (_brokerPremium.DiscountPercentage > 5 && bLoadForRenewal == false)
        //{
        //    ddlDiscountPercentage.Items.Clear();
        //    for (int p = _brokerPremium.DiscountPercentage; p >= 0; p--)
        //    {
        //        ddlDiscountPercentage.Items.Add(new ListItem(p.ToString() + " " + "%", p.ToString()));
        //    }
        //    //Updated on 06 May 2013 -- Start
        //    if (lblRenewalStaus.Text != string.Empty && lblRenewalStaus.Text != "0")
        //    {
        //        ddlDiscountPercentage.Items.Clear();
        //        for (int r = 7; r >= 0; r--)
        //        {
        //            ddlDiscountPercentage.Items.Add(new ListItem(r.ToString() + " " + "%", r.ToString()));
        //        }
        //    }
        //    //Updated on 06 May 2013 -- End
        //}

        chkSelected.Checked = _brokerPremium.SelectedStatus;
        ddlGarageType.Text = _brokerPremium.WorkShop;
        txtDeductible.Text = _brokerPremium.DEC;
        txtFireTheft.Text = _brokerPremium.FireTheft;
        txtOwnDamage.Text = _brokerPremium.OwnDamage;
        // *** Get Tesco ***
        if (_brokerPremium.TescoSelect == 2)
            chkGetTesco.Checked = true;
        // ******
        chkCTPL.Checked = _brokerPremium.IsIncludeCMI;
        //ไม่ต้องก็ได้นะ
        //chkCTPL_CheckedChanged(null, null);
        //แก้ๆ จะเข้า txtGrossPremium_TextChanged ท่าเดียว
        //เข้า ddlVehicleBodyType_SelectedIndexChanged ซ้ำๆทำไม
        txtCTPL.Enabled = chkCTPL.Checked;
        ddlVehicleBodyType.Enabled = chkCTPL.Checked;
        if (_brokerPremium.Info3 != string.Empty)
        {
            ddlVehicleBodyType.Text = _brokerPremium.Info3;
            // ไม่ต้องก็ได้นะ เยอะ ddlVehicleBodyType_SelectedIndexChanged(null, null);
            // สุดท้ายก็ใส่ค่าเดิม งง

            txtCTPL.Text = _brokerPremium.TotalCMI.ToString();
        }
        else
        {
            if (chkCTPL.Checked)
            {
                if (ddlVehicleBodyType.Text == "1")
                {
                    txtCTPL.Text = "645.21";
                }
                else if (ddlVehicleBodyType.Text == "2")
                {
                    txtCTPL.Text = "967.28";
                }
                else
                {
                    txtCTPL.Text = "0";
                }
            }
        }

        txtTPPD.Text = _brokerPremium.TPPD;
        txtTPBIA.Text = _brokerPremium.TPBIA;
        txtTPBIP.Text = _brokerPremium.TPBIP;
        txtBailBond.Text = _brokerPremium.BailBound;
        txtNetPremium.Text = _brokerPremium.Premium.ToString();
        txtGrossPremium.Text = _brokerPremium.TotalVMI.ToString();

        if (_brokerPremium.Info4 == "1")
        {
            chkCompanyStaff.Checked = true;
        }
        else
        {
            chkCompanyStaff.Checked = false;
        }

        txtFloodCoverAmount.Text = _brokerPremium.Info5;

        if (_brokerPremium.Info6 == "1")
        {
            chkNamedDriver.Checked = true;
        }
        else
        {
            chkNamedDriver.Checked = false;
        }

        txtAccModCost.Text = _brokerPremium.Info7;

        //ทำซ้ำทำไม งงเว้ย
        //Updated on 06 May 2013 -- Start
        //if (lblRenewalStaus.Text != string.Empty && lblRenewalStaus.Text != "0" && bLoadForRenewal == false)
        //{
        //    if (_brokerPremium.DiscountPercentage > 7)
        //        ddlDiscountPercentage.Text = "7";
        //    else
        //        ddlDiscountPercentage.SelectedIndex = ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue(_brokerPremium.DiscountPercentage.ToString()));
        //}
        //else
        //{
        //    ddlDiscountPercentage.SelectedIndex = ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue(_brokerPremium.DiscountPercentage.ToString()));
        //}
        //ddlDiscountPercentage_SelectedIndexChanged(null, null);
        //Updated on 06 May 2013 -- End
        
        if (_brokerPremium.TescoSelect != 2)
        {
            txtFinalAnnualPremium.Text = _brokerPremium.FinalAnnualPremium.ToString("#0.00");
        }
        else
        {
            float finAnnualP = _brokerPremium.FinalAnnualPremium - _brokerPremium.TescoAmount;
            txtFinalAnnualPremium.Text = finAnnualP.ToString("#0.00");
        }
        txtFinalAnnualPremiumNoDisc.Text = _brokerPremium.FinalAnnualPremiumNoDisc.ToString("#0.00");
        txtPA.Text = _brokerPremium.PADriver.ToString();
        txtMED.Text = _brokerPremium.MedicalExpense.ToString();
        txtEditLicensePlate.Text = _brokerPremium.Info2;
        lblEditLicensePlate.Text = _brokerPremium.Info2;
        txtPremiumChangeComments.Text = _brokerPremium.Info8;

        if (_brokerPremium.Bank != string.Empty && _brokerPremium.Bank != "-1")
        {
            ddlCreditCard.SelectedIndex = ddlCreditCard.Items.IndexOf(ddlCreditCard.Items.FindByValue(_brokerPremium.Bank));
        }

        if (_brokerPremium.NoofInstallment > 2)
        {
            ddlNoofInstallments.Items.Clear();
            ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
            ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
            ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
            ddlNoofInstallments.Items.Add(new ListItem("10" + " " + Resources.CarInsurance.Installment, "10"));
            ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));

            ddlNoofInstallments.Text = _brokerPremium.NoofInstallment.ToString();
        }

        ddlBrokerCoverType.Text = _brokerPremium.ProviderCoverTypeId.ToString();
        _discountPercentage = _brokerPremium.DiscountPercentage;
        // **** Start ****
        //ไม่ใช้ Method นี้แล้วเพราะว่า ddlBrokerCoverType_SelectedIndexChanged(null, null);
        // มี LoadBrokerDefault()ซึ่งไม่ต้องเอามาใหม่
        if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11")
        {
            chkMile.Enabled = true;
        }
        else
        {
            chkMile.Checked = false;
            chkMile.Enabled = false;
        }
        LoadDiscountPercentageList();
        LoadMonthlyInstallment();
        // **** End ****
        //ไม่ต้อง txtGrossPremium_TextChanged อีกรอบแล้วมั้ง

        ddlCreditCard_SelectedIndexChanged(null, null);
        //Yui@26/05/2014 : ddlCreditCard_SelectedIndexChanged already called the method
        //NoofInstallments_SelectedIndexChanged(null, null);

        if (_brokerPremium.PaymentOption != string.Empty && _brokerPremium.PaymentOption != "-1")
        {
            ddlPaymentOption.Text = _brokerPremium.PaymentOption;
        }
        lblB4EditFinalAnnualPremium.Text = _brokerPremium.OriginalPremiumWD.ToString("#0.00");
        lblB4EditFinalAnnualPremiumNoDisc.Text = _brokerPremium.OriginalPremiumWOD.ToString("#0.00");

        ddlPaymentMode.SelectedIndex = ddlPaymentMode.Items.IndexOf(ddlPaymentMode.Items.FindByValue(_brokerPremium.PaymentMode));

        //Yui@22/01/2015
        chkMile.Checked = _brokerPremium.Mile;

        // *** Get Tesco ***
        if (chkGetTesco.Checked == true)
            txtTescoAmount.Text = _brokerPremium.TescoAmount.ToString();
        // ******

        //if (_brokerPremium.FinalAnnualPremiumWD != (float)0)
        //    txtFinalAnnualPremium.Text = _brokerPremium.FinalAnnualPremiumWD.ToString("#0.00");
    }

    private void ClearFields()
    {
        txtPremiumId.Text = "0";
        txtNetPremium.Text = "";

        //ddlDiscountPercentage.Items.Clear();
        //ddlDiscountPercentage.Items.Add(new ListItem("0 %", "0"));
        //ddlDiscountPercentage.Text = "0";
        ddlDiscountPercentage.Items.Clear();
        for (int i = 5; i >= 0; i--)
        {
            ddlDiscountPercentage.Items.Add(new ListItem(i.ToString() + " " + "%", i.ToString()));
        }

        chkChangePremium.Checked = false;
        chkMile.Checked = false;
        ddlGarageType.Text = "-1";
        chkSelected.Checked = false;

        ddlBrokerProvider.Enabled = true;

        txtDeductible.Text = "";
        txtFireTheft.Text = "";

        chkCTPL.Checked = true;
        txtCTPL.Enabled = true;
        chkChangePremium.Checked = false;

        txtTPPD.Text = "";
        txtTPBIA.Text = "";
        txtTPBIP.Text = "";
        txtPA.Text = "";
        txtMED.Text = "";
        txtBailBond.Text = "";

        lblTax.Text = "0";
        lblVAT.Text = "0";
        lblDiscountAmount.Text = "0";
        lblAnnualPremium.Text = "0";
        lblNetPremium.Text = "0";
        txtGrossPremium.Text = "0";
        txtFinalAnnualPremium.Text = "0";
        txtFinalAnnualPremiumNoDisc.Text = "0";
        txtFinalAnnualPremium.ReadOnly = true;
        txtFinalAnnualPremiumNoDisc.ReadOnly = true;

        txtFloodCoverAmount.Text = "0";
        txtAccModCost.Text = "0";
        txtPremiumChangeComments.Text = string.Empty;

        //Monthly Installment -- Start
        lblTotalGrossPremiumWD.Text = "0";
        lblFirstInstallmentWD.Text = "0";
        lblLastInstallmentWD.Text = "0";
        lblTotalGrossPremiumWOD.Text = "0";
        lblFirstInstallmentWOD.Text = "0";
        lblLastInstallmentWOD.Text = "0";
        lblFirstInstallmentWDdesc.Text = string.Empty;
        lblFirstInstallmentWODdesc.Text = string.Empty;

        ddlNoofInstallments.Items.Clear();
        ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));

        ddlCreditCard.Items.Clear();
        ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));

        ddlGGDiscount.Items.Clear();
        ddlGGDiscount.Items.Add(new ListItem("0 %", "0"));

        //Monthly Installment -- End
        chkSelected.Enabled = true;

        chkGetTesco.Checked = false;
        chkGetTesco.Enabled = true;
        hidFinalAnnualPremium.Value = "";
    }

    private void ShowTescoAmount()
    {
        lblTesco.Text = "";
        string _strSelect = "";
        string strCommence = "";
        string minPremium = "0";
        string strctpl = "0";
        decimal _Premium = 0;
        decimal _ctpl = 0;
        MyDatabase _db = new MyDatabase();
        DataTable dt = new DataTable();
        DataTable _dtSelect = new DataTable();
        DateTime _CoverCommDate = dateTimeNow;
        DateTime _CurrentDate = dateTimeNow;
        TimeSpan ts;
        Int32 days = 0;
        minPremium = txtFinalAnnualPremium.Text;
        if (!decimal.TryParse(minPremium, out _Premium))
        {
            _Premium = 0;
        }
        if (chkCTPL.Checked)
        {
            strctpl = txtCTPL.Text;
        }
        if (!decimal.TryParse(strctpl, out _ctpl))
        {
            _ctpl = 0;
        }

        //Yui@30Jan2015 : Renew get same tesco discount as online
        //if (lblRenewalStaus.Text.Trim() != string.Empty && (lblRenewalStaus.Text.Trim() == "1" || lblRenewalStaus.Text.Trim() == "2"))
        //{
        //    txtTescoAmount.Text = "0";
        //}
        //else
        //{
        _strSelect = @" SELECT CoverageCommenceDate = CASE WHEN LEN(CD.Info19) > 0 THEN CD.Info19 ELSE CP.CoverageCommenceDate END ";
        _strSelect += " FROM tblCarPolicy CP INNER JOIN tblCarDetailTH CD ON CD.CarId = CP.CECarId ";
        _strSelect += " WHERE CP.CECarId = " + txtCarId.Text;
        _dtSelect = _db.GetDataTable(_strSelect);
        if (_dtSelect != null && _dtSelect.Rows.Count > 0)
        {
            strCommence = _dtSelect.Rows[0]["CoverageCommenceDate"].ToString();
        }
        if (!DateTime.TryParse(strCommence, out _CoverCommDate))
        {
            _CoverCommDate = new DateTime();
        }
        ts = (_CoverCommDate.Date - _CurrentDate.Date);
        days = ts.Days;
        txtTescoAmount.Text = "0";
        if (_Premium > 0 && _Premium <= 12000)
        {
            if (days > 60)
            {
                txtTescoAmount.Text = "200";
            }
        }
        else if (_Premium > 12000 && _Premium <= 15000)
        {
            if (days >= 15 && days <= 30)
            {
                txtTescoAmount.Text = "200";
            }
            else if (days > 30 && days <= 60)
            {
                txtTescoAmount.Text = "300";
            }
            else if (days > 60)
            {
                txtTescoAmount.Text = "400";
            }
        }
        else if (_Premium > 15000 && _Premium <= 20000)
        {
            if (days >= 15 && days <= 30)
            {
                txtTescoAmount.Text = "300";
            }
            else if (days > 30 && days <= 60)
            {
                txtTescoAmount.Text = "400";
            }
            else if (days > 60)
            {
                txtTescoAmount.Text = "600";
            }
        }
        else if (_Premium > 20000 && _Premium <= 30000)
        {
            if (days >= 15 && days <= 30)
            {
                txtTescoAmount.Text = "400";
            }
            else if (days > 30 && days <= 60)
            {
                txtTescoAmount.Text = "500";
            }
            else if (days > 60)
            {
                txtTescoAmount.Text = "700";
            }
        }
        else if (_Premium > 30000 && _Premium <= 40000)
        {
            if (days >= 15 && days <= 30)
            {
                txtTescoAmount.Text = "500";
            }
            else if (days > 30 && days <= 60)
            {
                txtTescoAmount.Text = "600";
            }
            else if (days > 60)
            {
                txtTescoAmount.Text = "800";
            }
        }
        else if (_Premium > 40000)
        {
            if (days >= 15 && days <= 30)
            {
                txtTescoAmount.Text = "600";
            }
            else if (days > 30 && days <= 60)
            {
                txtTescoAmount.Text = "700";
            }
            else if (days > 60)
            {
                txtTescoAmount.Text = "1000";
            }
        }
        //}

    }

    private void LoadBrokerProvider()
    {
        ddlBrokerProvider.Items.Clear();

        DataTable _dtBrokerProvider = General.GetComboItem("BrokerProvider", true);
        if (_dtBrokerProvider != null && _dtBrokerProvider.Rows.Count > 0)
        {
            ddlBrokerProvider.DataSource = _dtBrokerProvider;
            ddlBrokerProvider.DataTextField = _dtBrokerProvider.Columns[0].ColumnName.ToString();
            ddlBrokerProvider.DataValueField = _dtBrokerProvider.Columns[1].ColumnName.ToString();
            ddlBrokerProvider.DataBind();
        }

        ddlBrokerProvider.Items.Insert(0, new ListItem("Select", "-1"));
    }

    private void LoadBrokerCoverType()
    {
        //Yui@26Feb2015
        //lblPremiumError.Text = "";
        //lblPremiumMessage.Text = "";
        //ddlBrokerCoverType.Items.Clear();
        //MyDatabase _db = new MyDatabase();
        //DataTable _dtBrokerCoverType = new DataTable("tblBrokerCoverType");
        //_dtBrokerCoverType = _db.GetDataTable("Select ProviderCoverTypeID, " + Resources.DBTable.FieldName + " FROM tblCXBrokerProviderCoverType WHERE Status = 1 ORDER BY ProviderCoverTypeID");
        ////Yui@26/05/2014 : No Bank Customer
        ////if (ddlBrokerProvider.Text == "41" && txtUserTypeId.Text == "1001")
        ////{
        ////    _dtBrokerCoverType = _db.GetDataTable("Select ProviderCoverTypeID, " + Resources.DBTable.FieldName + " FROM tblCXBrokerProviderCoverType WHERE Status = 1 AND ProviderCoverTypeID<> 11 ORDER BY ProviderCoverTypeID");
        ////}
        //if (_dtBrokerCoverType != null && _dtBrokerCoverType.Rows.Count > 0)
        //{
        //    ddlBrokerCoverType.DataSource = _dtBrokerCoverType;
        //    ddlBrokerCoverType.DataTextField = _dtBrokerCoverType.Columns[1].ColumnName.ToString();
        //    ddlBrokerCoverType.DataValueField = _dtBrokerCoverType.Columns[0].ColumnName.ToString();
        //    ddlBrokerCoverType.DataBind();
        //}
        //*************

        ddlBrokerCoverType.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        ddlBrokerCoverType.Items.Insert(1, new ListItem(Resources.CarInsurance.Insurance_ClassOne, "10"));
        ddlBrokerCoverType.Items.Insert(2, new ListItem(Resources.CarInsurance.Insurance_ClassOneLowCost, "11"));
        ddlBrokerCoverType.Items.Insert(3, new ListItem(Resources.CarInsurance.Insurance_ClassTwo, "20"));
        ddlBrokerCoverType.Items.Insert(4, new ListItem(Resources.CarInsurance.Insurance_ClassTwoPlus, "21"));
        ddlBrokerCoverType.Items.Insert(5, new ListItem(Resources.CarInsurance.Insurance_ClassThree, "30"));
        ddlBrokerCoverType.Items.Insert(6, new ListItem(Resources.CarInsurance.Insurance_ClassThreePlus, "31"));
    }

    private void LoadAgentList()
    {
        //lblPremiumError.Text = "";
        //lblPremiumMessage.Text = "";
        try
        {
            MyDatabase _db = new MyDatabase();
            DataTable _dt = new DataTable("tblList");
            string _spName = "sprocCXCRMGetAgentList";
            SortedList paraList = new SortedList();
            paraList.Add("@AgentID", Session[General.UserId].ToString());
            _dt = _db.GetDataTableBySP(_spName, paraList);
            ddlCBAgentList.Items.Clear();
            if (_dt != null && _dt.Rows.Count > 0)
            {
                ddlCBAgentList.DataSource = _dt;
                ddlCBAgentList.DataTextField = "FULLNAME";
                ddlCBAgentList.DataValueField = "CEID";
                ddlCBAgentList.DataBind();
            }
        }
        catch (Exception)
        {
        }

        txtPremiumId.Text = "0";
        txtNetPremium.Text = "";
        ddlDiscountPercentage.Text = "0";

        ddlGarageType.Text = "-1";
        chkSelected.Checked = false;
    }

    #region GetAgentCallStatus
    //public string GetAgentCallStatus(string CECarId)
    //{
    //    string _Status = "None";
    //    MyDatabase _db = new MyDatabase();
    //    string strSql = "SELECT CallStatus FROM tblCXCINoMatchCallStatus WHERE CECarId = " + CECarId;
    //    string _AgentCallStatusId = "-1";
    //    object _result = _db.ExecuteScalarSqlStatement(strSql);
    //    if (_result != null)
    //    {
    //        _AgentCallStatusId = _result.ToString();
    //    }
    //    if (_AgentCallStatusId == "0")
    //    {
    //        _Status = "Negative";
    //    }
    //    else if (_AgentCallStatusId == "1")
    //    {
    //        _Status = "Positive";
    //    }
    //    else if (_AgentCallStatusId == "2")
    //    {
    //        _Status = "Follow-up";
    //    }
    //    return _Status;
    //}
    #endregion

    public string GetCallBackCount()
    {
        MyDatabase _db = new MyDatabase();
        string _spName = "sprocCXCRMGetCallBackCount";

        SortedList _paraList = new SortedList();
        _paraList.Add("@CustomerID", txtCustomerId.Text);
        _paraList.Add("@CallTypeID", lblCallType.Text);
        _paraList.Add("@AgentID", txtAgentId.Text);
        string _callBackCount = "0";
        object _result = _db.ExecuteScalarSP(_spName, _paraList);
        if (_result != null)
        {
            _callBackCount = _result.ToString();
        }

        return _callBackCount;
    }

    private NonGGPremiumListPDFOutput CreateNonGGPDFObject()
    {
        Int64 CECarId = Convert.ToInt64(txtCarId.Text);
        NonGGPremiumListPDFOutput _nonGGPdf = new NonGGPremiumListPDFOutput();

        _nonGGPdf.Title = "ใบเสนอราคาเบี้ยประกันรถยนต์";
        _nonGGPdf.Footer = "";//"For more information, please login to www.GluayGluay.com.";

        _nonGGPdf.CarId = txtCarId.Text;
        _nonGGPdf.CustomerName = lblName.Text + " " + lblLastName.Text;
        _nonGGPdf.CarPlateNumber = txtEditLicensePlate.Text;
        _nonGGPdf.Email = lblEmailAddress.Text;
        _nonGGPdf.DOB = lblDOB.Text;
        _nonGGPdf.Mobile = lblMobileNo.Text;
        _nonGGPdf.Gender = lblGender.Text;
        _nonGGPdf.Occupation = lblOccupation.Text;

        _nonGGPdf.CurrentInsurer = lblCurrentInsurer.Text;
        _nonGGPdf.CarMakeModel = lblCarMakeModel.Text;
        _nonGGPdf.CarModelYear = lblRegYear.Text;
        _nonGGPdf.AnyClaim = lblClaimInfo.Text;
        _nonGGPdf.CommnecementDate = ddlEditCoverCommencementDate.Text;
        lblEditCoverCommencementDate.Text = ddlEditCoverCommencementDate.Text;
        if (chkExtComDate.Checked && ddlExtComDate.SelectedIndex > 0)
        {
            _nonGGPdf.ExtComDate = ddlExtComDate.SelectedItem.Text;
        }

        _nonGGPdf.InsuranceType = lblInsuranceType.Text;
        _nonGGPdf.GarageType = lblGarageType.Text;
        _nonGGPdf.QuoteDateTime = lblRefModifiedDateTime.Text;
        _nonGGPdf.VehicleTypeUsage = lblVehicleType.Text;
        _nonGGPdf.IncludeCTPL = lblCTPL.Text;
        _nonGGPdf.NCB = ddlEditNCB.Text;

        Int16 IsThai = 1;
        if (chkIsEN.Checked)
        {
            IsThai = 0;
        }

        if (IsThai == 1)
        {
            _nonGGPdf.AgentName = Session[General.UserName].ToString();
            _nonGGPdf.AgentContactNo = Session[General.UserPhoneNo].ToString();
        }
        else
        {
            _nonGGPdf.AgentName = Session[General.UserNameEN].ToString();
            _nonGGPdf.AgentContactNo = Session[General.UserPhoneNoEN].ToString();
        }

        _nonGGPdf.AgentEmail = Session[General.SMTPReplyTo].ToString();
        if (ddlEditNamedDriver.Text != "0")
        {
            _nonGGPdf.NamedDriver = ddlEditNamedDriver.Text;
        }
        else
        {

            _nonGGPdf.NamedDriver = Resources.Proposal.No;
        }

        MyDatabase _db = new MyDatabase();
        SortedList _paraList = new SortedList();
        _paraList.Add("@CECarID", txtCarId.Text);
        _paraList.Add("@ProductType", "CIN");
        _paraList.Add("@RefCEUserId", "0");
        _paraList.Add("@LangOption", "1");

        DataTable _dtPremiumList = new DataTable("tblPremiumList");
        _dtPremiumList = _db.GetDataTableBySP("sprocCXBrokerPremiumSelectItemList", _paraList);

        if (_dtPremiumList != null)
        {
            _nonGGPdf.ResultGridTable = _dtPremiumList;

            _paraList.Clear();
            _paraList.Add("@AgentId", Session[General.UserId].ToString());
            DataTable _dtAgentList = new DataTable("tblAgentList");
            _dtAgentList = _db.GetDataTableBySP("sprocCXCRMAgentLicense", _paraList);
            if (_dtAgentList != null)
            {
                foreach (DataRow drAgentList in _dtAgentList.Rows)
                {
                    if (drAgentList["CEID"].ToString() == Session[General.UserId].ToString())
                    {
                        if (drAgentList["LicenseNo"] != DBNull.Value)
                            _nonGGPdf.AgentLicenseNo = drAgentList["LicenseNo"].ToString();
                    }
                    else
                    {
                        if (IsThai == 1)
                        {
                            _nonGGPdf.AgentSupervisor = drAgentList["AgentName"].ToString();
                        }
                        else
                        {
                            _nonGGPdf.AgentSupervisor = drAgentList["AgentNameEN"].ToString();
                        }

                        if (drAgentList["LicenseNo"] != DBNull.Value)
                            _nonGGPdf.AgentSupLicenseNo = drAgentList["LicenseNo"].ToString();
                    }
                }
            }

        }
        return _nonGGPdf;
    }

    private CashInstallmentPDFOutput CreateCashInstallmentPDFObject(string CarPlate, string ContractNo, string Premium1,
        string Premium2, string Premium3, string NoOfInstall, string Install1, string Install2, string Install3, string Install4,
        string InstallDate1, string InstallDate2, string InstallDate3, string InstallDate4, bool IsIncludeCMI)
    {
        Int64 CECarId = Convert.ToInt64(txtCarId.Text);
        CashInstallmentPDFOutput _cashInstallmentPdf = new CashInstallmentPDFOutput();
        _cashInstallmentPdf.CarPlate = CarPlate;
        _cashInstallmentPdf.ContractNo = ContractNo;
        _cashInstallmentPdf.Premium1 = Premium1;
        _cashInstallmentPdf.Premium2 = Premium2;
        _cashInstallmentPdf.Premium3 = Premium3;
        _cashInstallmentPdf.NoOfInstall = NoOfInstall;
        _cashInstallmentPdf.Install1 = Install1;
        _cashInstallmentPdf.Install2 = Install2;
        _cashInstallmentPdf.Install3 = Install3;
        _cashInstallmentPdf.Install4 = Install4;
        _cashInstallmentPdf.InstallDate1 = InstallDate1;
        _cashInstallmentPdf.InstallDate2 = InstallDate2;
        _cashInstallmentPdf.InstallDate3 = InstallDate3;
        _cashInstallmentPdf.InstallDate4 = InstallDate4;
        _cashInstallmentPdf.IsSCB = false;
        _cashInstallmentPdf.IsBBL = false;
        _cashInstallmentPdf.IsKBank = false;
        _cashInstallmentPdf.IsKTB = false;
        _cashInstallmentPdf.IsIncludeCMI = IsIncludeCMI;

        return _cashInstallmentPdf;
    }

    protected void btnPremiumDownload_Click(object sender, EventArgs e)
    {
        if (grvPremiumList.Rows.Count > 0)
        {
            NonGGPremiumListPDFOutput _nonGGPdf = CreateNonGGPDFObject();

            string _fileName = _nonGGPdf.GeneratePDF(Convert.ToString(Session["Language"]), chkIsPromotion.Checked);
            FileInfo file = new System.IO.FileInfo(_fileName);
            if (!file.Exists)
            {
                Response.StatusCode = 500;
                Response.End();
                return;
            }
            Response.Clear();
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetNoStore();
            Response.Cache.SetExpires(DateTime.MinValue);
            Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
            Response.AddHeader("Content-Length", file.Length.ToString());
            Response.ContentType = "application/octet-stream";
            Response.WriteFile(file.FullName);
            ApplicationInstance.CompleteRequest();
            Response.End();
        }
        else
        {
            ClientScript.RegisterStartupScript(btnPremiumDownload.GetType(), "DownloadPremiumAlert", "alert('No item to download!');", true);
        }
    }

    public string GetDownloadURl(Int64 CECarId, string VehicleNo)
    {
        string _url = "";
        string inputval = CECarId.ToString() + "@" + VehicleNo;
        _url = "javascript:OpenPremiumDownload('" + inputval + "');";
        return _url;
    }

    public void SetPremiumDownLoadLink()
    {
        string url = "PremiumDownload.aspx?carid=" + txtCarId.ToString();
        StringBuilder sb = new StringBuilder();
        sb.Append("<script>");
        sb.Append("window.open('" + url + "', '', '');");
        sb.Append("</scri");
        sb.Append("pt>");
        ClientScript.RegisterStartupScript(GetType(), "test", sb.ToString());
    }

    #region GeneratePremium
    //public void GeneratePremium(Int64 CECarId)
    //{

    //    Int32 _Count = 0;
    //    Label lblContent = new Label();
    //    string _html = "";
    //    string _fileName = "FileName";
    //    _fileName = "Premium_" + CECarId;
    //    string _UserCover = "";

    //    string _ProductType = "CIN";
    //    DataSet _dsPremium = new DataSet();
    //    BrokerPremiumDB _prokerpremiumdb = new BrokerPremiumDB();
    //    _dsPremium = _prokerpremiumdb.GetBrokerPremium(CECarId, _ProductType, Convert.ToInt16(lblLangOption.Text));
    //    if (_dsPremium.Tables[0].Rows.Count > 0)
    //    {
    //        if (_dsPremium.Tables.Count > 1)
    //        {
    //            if (_dsPremium.Tables[1].Rows.Count > 0)
    //            {
    //                _UserCover = _dsPremium.Tables[1].Rows[0]["ProviderCoverTypeDesc"].ToString();
    //            }
    //        }

    //        _Count = _dsPremium.Tables[0].Rows.Count;
    //        if (_Count > 4)
    //        {
    //            _Count = 4;
    //        }

    //        #region variables
    //        string[] _Insurer = new string[_Count];
    //        string[] _Workshop = new string[_Count];
    //        string[] _Premium = new string[_Count];
    //        string[] _Excess = new string[_Count];
    //        string[] _QuoteId = new string[_Count];
    //        string[] _Cover = new string[_Count];
    //        string[] _Package = new string[_Count];
    //        #endregion

    //        for (int i = 0; i < _Count; i++)
    //        {
    //            #region Values assign to variables
    //            _Insurer[i] = _dsPremium.Tables[0].Rows[i]["CompanyName"].ToString();
    //            _Workshop[i] = _dsPremium.Tables[0].Rows[i]["WorkShop"].ToString();
    //            _Premium[i] = "$" + _dsPremium.Tables[0].Rows[i]["Premium"].ToString();
    //            _Excess[i] = "$" + _dsPremium.Tables[0].Rows[i]["Excess"].ToString();
    //            _QuoteId[i] = CECarId.ToString();
    //            _Cover[i] = _dsPremium.Tables[0].Rows[i]["ProviderCoverTypeDesc"].ToString();
    //            _Package[i] = _dsPremium.Tables[0].Rows[i]["Package"].ToString();
    //            #endregion
    //        }

    //        #region Html

    //        Uri myUri = new Uri(HttpContext.Current.Request.Url.ToString());
    //        string domainUrl = "";
    //        string _strCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("CXCINMIsCXLive");
    //        if (_strCXLive == "2")
    //        {
    //            domainUrl = "http://" + myUri.Authority;
    //        }
    //        else
    //        {
    //            domainUrl = "http://" + myUri.Host;
    //        }
    //        string imgUrl = domainUrl + "/CX_Broker/images/header/kim_banner.png";

    //        _html = "<table style='width: 100%; background-color: white;' cellpadding='0' cellspacing='0'>"

    //                + "<tr>"
    //                + "<td align='left' style='width:100%'><img src='" + imgUrl + "' alt='KIM Brokers' /></td>"
    //                + "</tr>"

    //                + "<tr>"
    //                + "<td align='left' style='width:100%'>&nbsp;</td>"
    //                + "</tr>"

    //                + "<tr>"
    //                + "<td align='left' style='width:100%'>Below are the instant competitive quotations sourced from some insurers.</td>"
    //                + "</tr>"

    //                + "<tr>"
    //                + "<td align='left' style='width:100%'>&nbsp;</td>"
    //                + "</tr>"

    //                + "<tr>"

    //                + "<td align='left' style='width:100%'>Vehicle Number: " + "N/A" + "</td>"
    //                + "</tr>"

    //                + "<tr>"
    //                + "<td align='left' style='width:100%'>Type of Cover: " + _UserCover.ToString() + "</td>"
    //                + "</tr>"

    //                + "<tr>"
    //                + "<td align='left' style='width:100%'>&nbsp;</td>"
    //                + "</tr>"

    //                + "<tr>"
    //                + "<td align='left' style='width:100%'><b>QUOTES</b></td>"
    //                + "</tr>"

    //                + "<tr>"
    //                + "<td align='left' style='width:100%'>"
    //                + "<table style='width: 100%; background-color: white;' cellpadding='5' cellspacing='2' border='1'>"
    //                + "<tr>"
    //                + "<td align='left' style='width:150px'>&nbsp;</td>";
    //        for (int j = 1; j <= _Count; j++)
    //        {
    //            _html += "<td align='center' style='width:250px'>Quotation " + j + "</td>";
    //        }
    //        _html += "</tr>"

    //        + "<tr>"
    //        + "<td align='left' style='width:150px'>Quote ID</td>";
    //        for (int j = 1; j <= _Count; j++)
    //        {
    //            _html += "<td align='center' style='width:250px'> " + _QuoteId[j - 1].ToString() + "</td>";
    //        }
    //        _html += "</tr>"

    //        + "<tr>"
    //        + "<td align='left' style='width:150px'>Insurer</td>";
    //        for (int j = 1; j <= _Count; j++)
    //        {
    //            _html += "<td align='center' style='width:250px'> " + _Insurer[j - 1].ToString() + "</td>";
    //        }
    //        _html += "</tr>"

    //        + "<tr>"
    //        + "<td align='left' style='width:150px'>Restriction on Workshop</td>";
    //        for (int j = 1; j <= _Count; j++)
    //        {
    //            _html += "<td align='center' style='width:250px'> " + _Workshop[j - 1].ToString() + "</td>";
    //        }
    //        _html += "</tr>"

    //        + "<tr>"
    //        + "<td align='left' style='width:150px'>Cover Type</td>";
    //        for (int j = 1; j <= _Count; j++)
    //        {
    //            _html += "<td align='center' style='width:250px'> " + _Cover[j - 1].ToString() + "</td>";
    //        }
    //        _html += "</tr>"

    //        + "<tr>"
    //        + "<td align='left' style='width:150px'>Package</td>";
    //        for (int j = 1; j <= _Count; j++)
    //        {
    //            _html += "<td align='center' style='width:250px'> " + _Package[j - 1].ToString() + "</td>";
    //        }
    //        _html += "</tr>"

    //        + "<tr>"
    //        + "<td align='left' style='width:150px'>Premium</td>";
    //        for (int j = 1; j <= _Count; j++)
    //        {
    //            _html += "<td align='center' style='width:250px; color:blue; font-weight:bold;'> " + _Premium[j - 1].ToString() + "</td>";
    //        }
    //        _html += "</tr>"

    //        + "<tr>"
    //        + "<td align='left' style='width:150px'>Excess (Insured + Named Drivers)</td>";
    //        for (int j = 1; j <= _Count; j++)
    //        {
    //            _html += "<td align='center' style='width:250px; color:blue; font-weight:bold;'> " + _Excess[j - 1].ToString() + "</td>";
    //        }
    //        _html += "</tr>"
    //        + "</table>"
    //        + "</td>"
    //        + "</tr>"

    //        + "<tr>"
    //        + "<td align='left' style='width:100%'>&nbsp;</td>"
    //        + "</tr>"

    //        + "<tr>"
    //        + "<td align='left' style='width:100%'>&bull; This Quote Is Subject To the Insurer's Final Confirmation And Coverage Is Only Effective When The Insurer Has Accepted The Risk</td>"
    //        + "</tr>"

    //        + "<tr>"
    //        + "<td align='left' style='width:100%'>&bull; The Insurer Reserves The Right To Revise or Withdraw The Quote If Any Of the Information Given Differs From The Actual Risk</td>"
    //        + "</tr>"

    //        + "<tr>"
    //        + "<td align='left' style='width:100%'>&bull; Unless Otherwise Specified, The Quote Is Valid Only For 14 Days From The Date Of Quote</td>"
    //        + "</tr>"

    //        + "<tr>"
    //        + "<td align='left' style='width:100%'>&bull; All premiums quoted are nett, ie where applicable, inclusive of NCD, Safe Driver Discount and prevailing GST</td>"
    //        + "</tr>"

    //        + "</table>";
    //        #endregion

    //        string _HeaderText = "";

    //        Label lblPremiumHtml = new Label();
    //        lblPremiumHtml.Text = _html;
    //        ExportHtml(_fileName, lblPremiumHtml, _HeaderText);
    //    }
    //}

    //public void ExportHtml(string fileName, Label lblPremiumHtml, string headerText)
    //{
    //    string attachment = "attachment; filename=" + fileName + ".htm";
    //    Response.ClearContent();
    //    Response.AddHeader("content-disposition", attachment);
    //    Response.ContentType = "text/HTML";
    //    StringWriter sw = new StringWriter();
    //    HtmlTextWriter htw = new HtmlTextWriter(sw);
    //    HtmlForm frm = new HtmlForm();
    //    frm.InnerHtml = headerText;
    //    lblPremiumHtml.Parent.Controls.Add(frm);
    //    frm.Attributes["runat"] = "server";
    //    frm.Controls.Add(lblPremiumHtml);
    //    frm.RenderControl(htw);
    //    Response.Write(sw.ToString());
    //    Response.End();
    //}
    #endregion

    protected void btnReset_Click(object sender, EventArgs e)
    {
        Response.Redirect(lblResetUrl.Text.ToString());
    }

    protected void gvCallHistory_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {


            Int64 value = Convert.ToInt64(e.Row.Cells[2].Text);

            if (value.ToString() == txtCarId.Text)
            {
                e.Row.Cells[2].BackColor = System.Drawing.Color.FromName("#c6c6c6");
                e.Row.Cells[2].Font.Bold = true;
                e.Row.Cells[2].Font.Size = FontUnit.Medium;

                e.Row.Cells[4].BackColor = System.Drawing.Color.FromName("#c6c6c6");
                e.Row.Cells[4].Font.Bold = true;

                e.Row.BackColor = System.Drawing.Color.FromName("#ffffcc");
                e.Row.Height = Unit.Pixel(Convert.ToInt32(e.Row.Height.Value + 60d));

                lblCallHistoryFoundCount.Text = (Convert.ToInt32(lblCallHistoryFoundCount.Text) + 1).ToString();
                lblCallHistoryMessage.Text = "(" + lblCallHistoryFoundCount.Text + ") " + Resources.General.Callhistoryfound + "";
                lblCallHistoryFoundCount.Visible = false;

            }
            else
            {
                if (lblCallHistoryFoundCount.Text == "0")
                {
                    lblCallHistoryMessage.Text = Resources.General.Nocallhistoryfor + " " + Resources.CarInsurance.CarId + ": " + txtCarId.Text;
                }
            }

        }
        else if (lblCallHistoryFoundCount.Text == "0")
        {
            lblCallHistoryMessage.Text = Resources.General.Nocallhistoryfor + " " + Resources.CarInsurance.CarId + ": " + txtCarId.Text;
            lblCallHistoryFoundCount.Visible = false;
        }
    }


    #region GetHoliday

    //private int GetNoOfHoliday(int NoOfDay)
    //{
    //    int _retValue = 0;
    //    MyDatabase _db = new MyDatabase();
    //    string spName = "[sprocCXCRMAgentCalenderGetEventsCount]";
    //    SortedList paraList = new SortedList();
    //    DateTime startDate = dateTimeNow;
    //    DateTime endDate = dateTimeNow.AddDays(NoOfDay);
    //    paraList.Add("@StartDate", startDate.ToString("yyyyMMdd"));
    //    paraList.Add("@EndDate", endDate.ToString("yyyyMMdd"));
    //    object eventCount = _db.ExecuteScalarSP(spName, paraList);
    //    if (eventCount != null)
    //    {
    //        _retValue = Convert.ToInt32(eventCount);
    //    }
    //    return _retValue;
    //}

    //private int GetNoOfCallBackDays()
    //{
    //    int _noOfDays = 4;
    //    if (Session[General.IsRenewalAgent].ToString() == "1")
    //    {
    //        _noOfDays = 21;
    //    }

    //    _noOfDays = _noOfDays + GetNoOfHoliday(_noOfDays);
    //    DateTime chkDate = dateTimeNow;
    //    int _tempNoOfDays = _noOfDays;

    //    for (int i = 1; i < _tempNoOfDays; i++)
    //    {
    //        chkDate = dateTimeNow.AddDays(i);

    //        if (chkDate.Date.DayOfWeek == DayOfWeek.Saturday || chkDate.Date.DayOfWeek == DayOfWeek.Sunday)
    //        {
    //            _noOfDays++;
    //        }
    //    }
    //    return _noOfDays;
    //}

    #endregion

    protected void csvTargetDate_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (rdoCallBack.Checked || trCallBack1.Visible == true)
        {
            string _strTargetDateTime = txtTargetDate.Text + " " + ddlTHour.Text + ":" + ddlTMin.Text;
            DateTime _dtTargetDateTime = dateTimeNow;

            //int _noOfDays = GetNoOfCallBackDays();
            DateTime _dtLimitDateTime = GetCallBackDateLimit(15); //dateTimeNow.Date.AddDays(_noOfDays);
            _dtLimitDateTime = new DateTime(_dtLimitDateTime.Year, _dtLimitDateTime.Month, _dtLimitDateTime.Day, 23, 59, 59);

            if (ddlCICallStatus.Text == "10")
            {
                //ddlCIMainCallStatus.Text == "7" && 
                //_dtLimitDateTime = dateTimeNow.AddDays(60);
                //_strTargetDateTime = txtTargetDate.Text + " " + ddlTHour.Text + ":" + ddlTMin.Text; ;
                //11Mar2014
                DateTime _dtEditCoverCommDate = Convert.ToDateTime(lblEditCoverCommencementDate.Text);
                _dtEditCoverCommDate = new DateTime(_dtEditCoverCommDate.Year, _dtEditCoverCommDate.Month, _dtEditCoverCommDate.Day, dateTimeNow.Hour, dateTimeNow.Minute, dateTimeNow.Second);

                TimeSpan timespan = (_dtEditCoverCommDate - dateTimeNow);
                if (timespan.TotalDays < 60)
                {
                    args.IsValid = false;
                    csvTargetDate.ErrorMessage = Resources.General.CommencementCheck;
                    lblCallStatusMessage.Text = Resources.General.CommencementCheck;
                    return;
                }
                else
                {
                    //Can call back any time
                    _dtLimitDateTime = dateTimeNow;
                }
            }

            if (DateTime.TryParse(_strTargetDateTime, out _dtTargetDateTime))
            {
                if (DateTime.Compare(dateTimeNow, _dtTargetDateTime) <= 0)
                {
                    txtCallBackDateTime.Text = _dtTargetDateTime.ToString("dd/MMM/yyyy hh:mm:ss tt");

                    if (ddlCICallStatus.Text != "10")
                    {
                        if (DateTime.Compare(_dtTargetDateTime, _dtLimitDateTime) <= 0)
                        {
                            args.IsValid = true;
                        }
                        else
                        {
                            args.IsValid = false;
                            csvTargetDate.ErrorMessage = Resources.General.CallBackDateTimeInvalid + " " + Resources.General.CallBackDaysLimitMessage;
                            lblCallStatusMessage.Text = Resources.General.CallBackDateTimeInvalid + " " + Resources.General.CallBackDaysLimitMessage;
                        }
                    }
                    else
                    {
                        //ddlCIMainCallStatus.Text == "7" && 
                        if (DateTime.Compare(_dtTargetDateTime, _dtLimitDateTime) > 0)
                        {
                            args.IsValid = true;
                        }
                        else
                        {
                            args.IsValid = false;
                            csvTargetDate.ErrorMessage = "วันที่โทรกลับต้องมากกว่าวันที่ปัจจุบัน";
                            lblCallStatusMessage.Text = "วันที่โทรกลับต้องมากกว่าวันที่ปัจจุบัน";
                        }
                    }
                }
                else
                {
                    args.IsValid = false;
                    if (ddlCICallStatus.Text != "10")
                    {
                        csvTargetDate.ErrorMessage = Resources.General.CallBackDateTimeOlder;
                        lblCallStatusMessage.Text = Resources.General.CallBackDateTimeOlder;
                    }
                    else
                    {
                        //ddlCIMainCallStatus.Text == "7" && 
                        csvTargetDate.ErrorMessage = Resources.General.CommencementCheck;
                        lblCallStatusMessage.Text = Resources.General.CommencementCheck;
                    }
                }
            }
            else
            {
                args.IsValid = false;
                txtCallBackDateTime.Text = "0";
                if (ddlCICallStatus.Text != "10")
                {
                    csvTargetDate.ErrorMessage = Resources.General.CallBackDateTimeInvalid;
                    lblCallStatusMessage.Text = Resources.General.CallBackDateTimeInvalid;
                }
                else
                {
                    //ddlCIMainCallStatus.Text == "7" && 
                    csvTargetDate.ErrorMessage = Resources.General.CommencementCheck;
                    lblCallStatusMessage.Text = Resources.General.CommencementCheck;
                }
            }
        }
    }

    protected void btnNext_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/SiteUserHome.aspx");
    }

    protected void grvPremiumList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("MyDelete"))
        {
            if (e.CommandArgument != null)
            {
                if (lblCarMoreDetailID.Text == "-1")
                {
                    Int64 _AgentId = 0;
                    Int64 _CXBrokerPremiumId = 0;
                    _CXBrokerPremiumId = Convert.ToInt64(e.CommandArgument);
                    _AgentId = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());

                    MyDatabase _db = new MyDatabase();
                    SortedList _paraList = new SortedList();
                    _paraList.Add("@CXBrokerPremiumId", _CXBrokerPremiumId);
                    _paraList.Add("@AgentId", _AgentId);
                    int _effCount = _db.ExecuteNonSqlSP("sprocCXBrokerPremiumDeleteSingleItem", _paraList);
                    if (_effCount > 0)
                    {
                        ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Delete was successful.');", true);
                    }

                    grvPremiumList.DataBind();

                    if (grvPremiumList.Rows.Count > 0)
                    {
                        lblAppStatusMessage.Text = "( " + grvPremiumList.Rows.Count.ToString() + " ) record(s) found.";
                        chkConfirmEmail.Checked = false;
                        chkConfirmEmail_CheckedChanged(null, null);
                    }
                    else
                    {
                        lblAppStatusMessage.Text = "No records found.";
                    }

                    //lblPremiumError.Text = "";
                    //lblPremiumMessage.Text = "";
                    txtPremiumId.Text = "0";
                    txtNetPremium.Text = "";
                    ddlDiscountPercentage.Text = "0";

                    ddlGarageType.Text = "-1";
                    chkSelected.Checked = false;
                    ddlBrokerProvider.SelectedIndex = 0;
                    ddlBrokerCoverType.SelectedIndex = 0;
                    ddlBrokerProvider_SelectedIndexChanged(null, null);
                    uplPremiumList.Update();
                }
                else
                {
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Delete failed. Found application details.');", true);
                }
            }
        }
    }

    protected void btnEditSubmit_Click(object sender, EventArgs e)
    {
        if (Convert.ToInt32(lblCarMoreDetailID.Text) > 0)
        {
            btnSubmitPremium.Enabled = false;
            btnNewPremium.Enabled = false;
            btnEditSubmit.Enabled = false;
            lblPremiumMessage.Text = Resources.General.NonGGFoundAppDetailSubmission;
            lblPremiumMessage.ForeColor = System.Drawing.Color.Red;
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.NonGGFoundAppDetailSubmission + "');", true);
            return;
        }

        Page.Validate("editdetail");
        if (Page.IsValid)
        {
            MyDatabase _myDB = new MyDatabase();

            string _strUpdateSQL = "UPDATE tblCarDetailTH SET ";

            _strUpdateSQL += " Info15 = '" + txtEditLicensePlate.Text + "', ";
            _strUpdateSQL += " Info16 = '" + ddlEditNCB.Text + "', ";
            _strUpdateSQL += " Info17 = '" + ddlEditNamedDriver.Text + "', ";
            //_strUpdateSQL += " Info18 = '" + txtEditSumInsuredAmount.Text + "', ";
            _strUpdateSQL += " Info19 = '" + ddlEditCoverCommencementDate.Text + "' ";
            if (chkExtComDate.Checked == true)
            {
                if (ddlExtComDate.SelectedIndex > 0)
                {
                    _strUpdateSQL += ", Dinfo2 = '" + ddlExtComDate.SelectedValue + "' ";
                }
                else
                {
                    _strUpdateSQL += ", Dinfo2 = NULL ";
                }
            }
            else
            {
                _strUpdateSQL += ", Dinfo2 = NULL ";
            }
            _strUpdateSQL += " ,Ninfo5 = " + ddlHowUKnowUs.SelectedValue + " ";
            _strUpdateSQL += " WHERE CarID = " + txtCarId.Text + " AND RefCEUserID = " + txtCustomerId.Text;

            int _retValue = _myDB.ExecuteNonSqlStatement(_strUpdateSQL);
            if (_retValue > 0)
            {
                lblEditDetailMessage.Text = "Updating succeeded";
                lblEditLicensePlate.Text = txtEditLicensePlate.Text;
                lblEditCoverCommencementDate.Text = ddlEditCoverCommencementDate.Text;
                lblEditCoverCommencementDateMessage.Text = string.Empty;

                LoadDiscountPercentageList();
            }
            else
            {
                lblEditDetailMessage.Text = "Updating failed";
            }

        }
    }

    private void CheckQuoteStatus()
    {
        lblCommenceDateStatusMessage.Visible = false;
        lblQuoteDateTimeStatusMessage.Visible = false;

        if (lblCommenceDateStatus.Text == "0" && lblQuoteDateTimeStatus.Text == "1")
        {
            lblQuoteStatusMessage.Text = lblCommenceDateStatusMessage.Text;
            lblQuoteStatusMessage.Font.Bold = true;
            lblQuoteStatusMessage.ForeColor = System.Drawing.Color.Red;
        }
        else if (lblQuoteDateTimeStatus.Text == "0" && lblCommenceDateStatus.Text == "1")
        {
            lblQuoteStatusMessage.Text = lblQuoteDateTimeStatusMessage.Text;
            lblQuoteStatusMessage.Font.Bold = true;
            lblQuoteStatusMessage.ForeColor = System.Drawing.Color.Red;
        }
        else if (lblQuoteDateTimeStatus.Text == "0" && lblCommenceDateStatus.Text == "0")
        {
            lblQuoteDateTimeStatusMessage.Visible = false;
            lblCommenceDateStatusMessage.Visible = false;
            lblQuoteStatusMessage.Text = Resources.General.CommencementOVER;
            lblQuoteStatusMessage.Font.Bold = true;
            lblQuoteStatusMessage.ForeColor = System.Drawing.Color.Red;
        }
        else
        {
            lblQuoteDateTimeStatusMessage.Visible = false;
            lblCommenceDateStatusMessage.Visible = false;
            lblQuoteStatusMessage.Text = Resources.General.EverythingOK;
            lblQuoteStatusMessage.Font.Bold = true;
            lblQuoteStatusMessage.ForeColor = System.Drawing.Color.Green;
        }

        divBuyNowStatusMessage.Visible = true;

    }

    private void CheckApplicationStatus()
    {
        MyDatabase _db = new MyDatabase();
        SortedList _paraList = new SortedList();
        _paraList.Add("@CECarID", txtCarId.Text);
        _paraList.Add("@CustomerID", txtCustomerId.Text);
        DataTable _dtApp = new DataTable("tblApp");
        _dtApp = _db.GetDataTableBySP("sprocCXCRMNonGGApplicationStatusSelectItem", _paraList);

        if (_dtApp != null && _dtApp.Rows.Count > 0)
        {
            lblCarMoreDetailID.Text = _dtApp.Rows[0]["CECarMoreDetailId"].ToString();
            lblAppStatus.Text = string.Empty;

            lblAppStatusMessage.Text = string.Empty;
            lblAppStatusMessage.Text = Resources.General.NonGGFoundAppDetailSubmission;
            lblAppStatusMessage.ForeColor = System.Drawing.Color.Red;
            lblAppStatusMessage.Font.Bold = true;

            ddlBrokerProvider.SelectedIndex = ddlBrokerProvider.Items.IndexOf(ddlBrokerProvider.Items.FindByValue(_dtApp.Rows[0]["ProviderCompanyId"].ToString()));
            ddlBrokerProvider_SelectedIndexChanged(null, null);
            ddlBrokerCoverType.Text = _dtApp.Rows[0]["InsuranceType"].ToString();
            ddlBrokerCoverType_SelectedIndexChanged(null, null);

            ddlBrokerCoverType.Enabled = false;
            ddlBrokerProvider.Enabled = false;
            chkCTPL.Enabled = false;
            txtCTPL.Enabled = false;
            txtGrossPremium.Enabled = false;
            txtFinalAnnualPremium.Enabled = false;


            txtEditLicensePlate.Enabled = false;
            ddlEditNCB.Enabled = false;

            ddlEditNamedDriver.Enabled = false;

            ddlGarageType.Enabled = false;
            chkSelected.Enabled = false;
            SetGVPremiumSelectedIndex();

            lblCarMoreDetailID.Visible = false;
            lblAppStatus.Visible = false;
            btnSubmitPremium.Enabled = false;
            btnEditSubmit.Enabled = false;
            chkConfirmEmail.Visible = false;
        }
        else
        {
            SetGVPremiumSelectedIndex();
            ddlBrokerCoverType.Enabled = true;
            ddlBrokerProvider.Enabled = true;
            chkCTPL.Enabled = true;
            txtCTPL.Enabled = true;
            txtGrossPremium.Enabled = true;
            txtFinalAnnualPremium.Enabled = true;
            ddlDiscountPercentage.Enabled = true;

            txtEditLicensePlate.Enabled = true;
            ddlEditNCB.Enabled = true;
            ddlEditNamedDriver.Enabled = true;

            ddlGarageType.Enabled = true;
            chkSelected.Enabled = true;
            lblCarMoreDetailID.Text = "-1";
            lblAppStatus.Text = string.Empty;
            btnSubmitPremium.Enabled = true;
            btnEditSubmit.Enabled = true;
            lblAppStatusMessage.Text = string.Empty;
            if (grvPremiumList.Rows.Count > 0)
            {
                lblAppStatusMessage.Text = "( " + grvPremiumList.Rows.Count.ToString() + " ) record(s) found.";
                chkConfirmEmail.Checked = false;
                chkConfirmEmail_CheckedChanged(null, null);
            }
            else
            {
                lblAppStatusMessage.Text = "No records found.";
            }

            lblAppStatusMessage.ForeColor = System.Drawing.Color.Red;
            lblAppStatusMessage.Font.Bold = true;

        }
    }

    private void SetGVPremiumSelectedIndex()
    {
        foreach (GridViewRow myRow in grvPremiumList.Rows)
        {
            string _selectStatus = myRow.Cells[13].Text.ToString().ToLower();

            if (_selectStatus == "yes")
            {
                grvPremiumList.SelectedIndex = myRow.RowIndex;
                myRow.Cells[10].ForeColor = System.Drawing.Color.Red;
                lblSelectedRefNo.Text = myRow.Cells[5].Text.ToString();

                break;
            }
        }
    }

    protected void btnGoToNonGGPendingApp_Click(object sender, EventArgs e)
    {
        string _calltype = "&calltype=" + lblCallType.Text;
        if (lblSelectedRefNo.Text != string.Empty)
        {
            if (lblRenewalStaus.Text == "0")
            {
                Response.Redirect("~/carinsurance/offline/NonGGPackageApplication.aspx?refno=" + lblQRefNo.Text + _calltype);
            }
            else
            {
                if (lblLastYearRefNo.Text != string.Empty)
                {
                    Response.Redirect("~/carinsurance/offline/NonGGPackageApplication.aspx?refno=" + lblQRefNo.Text + "&lyrrefno=" + lblLastYearRefNo.Text + _calltype);
                }
            }
        }
        else
        {
            Int32 _CancelStatus = 0;
            string _QuoteRefNo = "";
            MyDatabase _db = new MyDatabase();
            string _strSelect = @"SELECT CASE WHEN MD.CancelStatus IS NULL THEN 0 ELSE MD.CancelStatus END AS CancelStatus "
                                + "FROM tblNonGGCarMoreDetails MD INNER JOIN tblCXBrokerPremium BR ON BR.CECarId = MD.CECarId AND BR.SelectedStatus = 1 "
                                + "WHERE BR.CECarId = " + txtCarId.Text;
            DataTable _dtSelect = new DataTable("dtSelect");
            _dtSelect = _db.GetDataTable(_strSelect);
            if (_dtSelect != null && _dtSelect.Rows.Count > 0)
            {
                _CancelStatus = Convert.ToInt32(_dtSelect.Rows[0]["CancelStatus"].ToString());
            }

            _dtSelect = null;
            _dtSelect = new DataTable("dtSelect");
            _strSelect = @"SELECT Info1 AS QuoteRefNo FROM tblCXBrokerPremium WHERE SelectedStatus = 1  AND CECarId = " + txtCarId.Text;
            _dtSelect = _db.GetDataTable(_strSelect);
            if (_dtSelect != null && _dtSelect.Rows.Count > 0)
            {
                _QuoteRefNo = _dtSelect.Rows[0]["QuoteRefNo"].ToString();
            }
            if (_CancelStatus == 0 && _QuoteRefNo.ToString() != string.Empty)
            {
                if (lblRenewalStaus.Text == "0")
                {
                    Response.Redirect("~/carinsurance/offline/NonGGPackageApplication.aspx?refno=" + _QuoteRefNo.ToString() + _calltype);
                }
                else
                {
                    if (lblLastYearRefNo.Text != string.Empty)
                    {
                        Response.Redirect("~/carinsurance/offline/NonGGPackageApplication.aspx?refno=" + _QuoteRefNo.ToString() + "&lyrrefno=" + lblLastYearRefNo.Text + _calltype);
                    }
                }
            }
            else
            {
                if (hidLastTab.Value != "3")
                {
                    lblPremiumMessage.Text = "Please select a quotation for customer.";
                    lblPremiumMessage.ForeColor = System.Drawing.Color.Red;
                }
                else
                {
                    hidLastTab.Value = "";
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Please select a quotation for customer.');", true);
                }
            }
        }
    }

    protected void txtGrossPremium_TextChanged(object sender, EventArgs e)
    {
        try
        {
            //System.Threading.Thread.Sleep(10000);
            decimal _premium = 0;

            if (decimal.TryParse(txtGrossPremium.Text, out _premium))
            {
                decimal _netPremiumround = 0;
                txtVAT.Text = "";
                txtTax.Text = "";
                txtNetPremium.Text = "";
                txtAnnualPremium.Text = "";
                lblTax.Text = "0";
                lblVAT.Text = "0";
                lblNetPremium.Text = "0";
                lblAnnualPremium.Text = "0";

                if (_premium <= 5000)
                {
                    ddlDiscountPercentage.Text = "0";
                    ddlDiscountPercentage.Enabled = false;
                }
                else
                {
                    ddlDiscountPercentage.Enabled = true;
                    //if (ddlBrokerProvider.SelectedValue == "41" && ddlBrokerCoverType.SelectedValue == "11")
                    //{
                    //    if (_premium <= 5900 || _premium == 7900)
                    //    {
                    //        ddlDiscountPercentage.Text = "0";
                    //        ddlDiscountPercentage.Enabled = false;
                    //    }
                    //}
                }

                decimal _grossPremium = _premium;

                decimal _netPremium = _premium / 1.07M / 1.004M;

                _netPremium = Math.Floor(_netPremium); //Sakthi Add on 02 May 2013
                _netPremium = Math.Round(_netPremium); //Sakthi Add on 02 May 2013

                txtNetPremium.Text = _netPremium.ToString("#0.00");

                decimal _tax = 0;

                _tax = Convert.ToDecimal(_netPremium * (0.4M / 100.0M));

                _tax = Math.Ceiling(_tax);

                if (_tax >= 1000)
                {
                    lblTax.Text = _tax.ToString("#,000.00");
                }
                else
                {
                    lblTax.Text = _tax.ToString("#0.00");
                }

                txtTax.Text = _tax.ToString("#0.00");

                decimal _vat = 0;
                _vat = Convert.ToDecimal((_netPremium + _tax) * Convert.ToDecimal(7.0 / 100.0));


                if (_vat >= 1000)
                {
                    lblVAT.Text = _vat.ToString("#,000.00");
                }
                else
                {
                    lblVAT.Text = _vat.ToString("#0.00");
                }

                txtVAT.Text = _vat.ToString("#0.00");

                if (_netPremium >= 1000)
                {
                    lblNetPremium.Text = _netPremium.ToString("#,000.00");
                }
                else
                {
                    lblNetPremium.Text = _netPremium.ToString("#0.00");
                }
                _netPremium = _grossPremium - (_vat + _tax); //Sakthi Add on 02 May 2013

                decimal _annualPremium = 0;
                decimal _annualPremiumNoDisc = 0;

                _annualPremiumNoDisc = _netPremium + _vat + _tax;
                _netPremiumround = Math.Round(_netPremium); //Sakthi Add on 02 May 2013
                _netPremiumround = Math.Floor(_netPremiumround); //Sakthi Add on 02 May 2013

                if (_annualPremiumNoDisc < 5000) //Sakthi on 29 Apr 2013 //16 May 2013 -- change amount 10000 to 5000
                {
                    if (lblRenewalStaus.Text == string.Empty || lblRenewalStaus.Text == "0")
                    {
                        ddlDiscountPercentage.Text = "0";
                        ddlDiscountPercentage.Enabled = false;
                    }
                }
                if (ddlDiscountPercentage.Text != "0" && Convert.ToInt32(ddlDiscountPercentage.Text) > 0)
                {
                    decimal _discountAmount = Convert.ToDecimal((_netPremiumround * Convert.ToDecimal(Convert.ToDecimal(ddlDiscountPercentage.Text) / 100.0M)));

                    if (_discountAmount >= 1000)
                    {
                        lblDiscountAmount.Text = _discountAmount.ToString("#,000.00");
                    }
                    else
                    {
                        lblDiscountAmount.Text = _discountAmount.ToString("#0.00");
                    }
                    _annualPremium = (_netPremiumround + _vat + _tax) - _discountAmount;
                }
                else
                {
                    lblDiscountAmount.Text = "0";
                    _annualPremium = _netPremium + _vat + _tax;
                }

                if (_annualPremium >= 1000)
                {
                    lblAnnualPremium.Text = _annualPremium.ToString("#,000.00");
                }
                else
                {
                    lblAnnualPremium.Text = _annualPremium.ToString("#0.00");
                }

                //Added on 04 Oct 2012 
                if (chkCTPL.Checked)
                {
                    _annualPremium = _annualPremium + Convert.ToDecimal(txtCTPL.Text);
                    _annualPremiumNoDisc = _annualPremiumNoDisc + Convert.ToDecimal(txtCTPL.Text);
                }

                txtAnnualPremium.Text = _annualPremium.ToString("#0.00");
                txtFinalAnnualPremium.Text = _annualPremium.ToString("#0.00");
                txtFinalAnnualPremiumNoDisc.Text = _annualPremiumNoDisc.ToString("#0.00");

                lblB4EditFinalAnnualPremium.Text = _annualPremium.ToString("#0.00");
                lblB4EditFinalAnnualPremiumNoDisc.Text = _annualPremiumNoDisc.ToString("#0.00");

                InstallmentsCalculation();
                ShowTescoAmount(); //14 Jun 2013

                //******* Tesco & GG World Cup ***********
                if (chkGetTesco.Checked && (txtTescoAmount.Text != "" || txtTescoAmount.Text != "0"))
                {
                    _annualPremium = _annualPremium - Convert.ToDecimal(txtTescoAmount.Text);
                }

                txtFinalAnnualPremium.Text = _annualPremium.ToString("#0.00");
                //**************** End *******************

                // 2-27 Feb : New promotion 
                SetDiscountPremium();
            }
        }
        catch (Exception Ex)
        {
            lblPremiumError.Text = Ex.Message;
            Ex = null;
        }
    }

    private void SetDiscountPremium()
    {
        // ****** 2-27 Feb 2015 ******
        // 8% NEW Motor Insurance 
        // 9% Class 1 Motor Insurance Renewal 
        // For all insurance except class3
        // Premium >= 6,000
        // ************ End **********
        
        //if (txtFinalAnnualPremium.Text.Trim() != "" && int.Parse(dateTimeNow.ToString("yyyyMM")) == 201503)
        //{
            string discount = ddlDiscountPercentage.SelectedValue;
            decimal _annualPremium = Convert.ToDecimal(txtFinalAnnualPremium.Text);
            if (lblRenewalStaus.Text == "1" || lblRenewalStaus.Text == "2")
            {
                //Renew
                if (ddlBrokerCoverType.SelectedValue != "30" && _annualPremium >= 6000)
                {
                    if (ddlDiscountPercentage.Items.Count <= 10)
                    {
                        if (ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("6")) == -1)
                            ddlDiscountPercentage.Items.Insert(0, new ListItem("6 %", "6"));

                        if (ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("7")) == -1)
                            ddlDiscountPercentage.Items.Insert(0, new ListItem("7 %", "7"));

                        if (ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("8")) == -1)
                            ddlDiscountPercentage.Items.Insert(0, new ListItem("8 %", "8"));

                        if (ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("9")) == -1)
                            ddlDiscountPercentage.Items.Insert(0, new ListItem("9 %", "9"));
                    }
                    else
                    {
                        if (ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("6")) == -1)
                            ddlDiscountPercentage.Items.Insert(6, new ListItem("6 %", "6"));

                        if (ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("7")) == -1)
                            ddlDiscountPercentage.Items.Insert(6, new ListItem("7 %", "7"));

                        if (ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("8")) == -1)
                            ddlDiscountPercentage.Items.Insert(6, new ListItem("8 %", "8"));

                        if (ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("9")) == -1)
                            ddlDiscountPercentage.Items.Insert(6, new ListItem("9 %", "9"));
                    }

                    //if (_discountPercentage == 0)
                    //    ddlDiscountPercentage.SelectedIndex = ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("0"));
                }
                else if (ddlBrokerCoverType.SelectedValue == "30" || _annualPremium < 6000)
                {
                    if (ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("8")) > -1)
                    {
                        ddlDiscountPercentage.Items.RemoveAt(ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("8")));
                    }

                    if (ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("9")) > -1)
                    {
                        ddlDiscountPercentage.Items.RemoveAt(ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("9")));
                    }
                }

            }
            else
            {
                //Online
                if (ddlBrokerCoverType.SelectedValue != "30" && _annualPremium >= 6000)
                {
                    if (ddlDiscountPercentage.Items.Count <= 9)
                    {
                        if (ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("6")) == -1)
                            ddlDiscountPercentage.Items.Insert(0, new ListItem("6 %", "6"));

                        if (ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("7")) == -1)
                            ddlDiscountPercentage.Items.Insert(0, new ListItem("7 %", "7"));

                        if (ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("8")) == -1)
                            ddlDiscountPercentage.Items.Insert(0, new ListItem("8 %", "8"));
                    }
                    else
                    {
                        if (ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("6")) == -1)
                            ddlDiscountPercentage.Items.Insert(7, new ListItem("6 %", "6"));

                        if (ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("7")) == -1)
                            ddlDiscountPercentage.Items.Insert(7, new ListItem("7 %", "7"));

                        if (ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("8")) == -1)
                            ddlDiscountPercentage.Items.Insert(7, new ListItem("8 %", "8"));
                    }

                    //if (_discountPercentage == 0)
                    //    ddlDiscountPercentage.SelectedIndex = ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("0"));
                }
                else if (ddlBrokerCoverType.SelectedValue == "30" || _annualPremium < 6000)
                {
                    if (ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("6")) > -1)
                    {
                        ddlDiscountPercentage.Items.RemoveAt(ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("6")));
                    }

                    if (ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("7")) > -1)
                    {
                        ddlDiscountPercentage.Items.RemoveAt(ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("7")));
                    }

                    if (ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("8")) > -1)
                    {
                        ddlDiscountPercentage.Items.RemoveAt(ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue("8")));
                    }
                }

                if (txtPromotion.Text == "3")
                {
                    ddlDiscountPercentage.Items.Insert(0, new ListItem("10 %", "10"));
                }
            }

            if (_discountPercentage > 0)
            {
                ddlDiscountPercentage.SelectedIndex = ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue(_discountPercentage.ToString()));
            }
            else
            {
                ddlDiscountPercentage.SelectedIndex = ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue(discount));
            }
        //}
    }

    protected void ddlGarageType_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadBrokerDefault();//Sop Create method and updated on 16 Nov 2012 from BKK
    }

    protected void ddlDiscountPercentage_SelectedIndexChanged(object sender, EventArgs e)
    {
        txtGrossPremium_TextChanged(sender, e);
        if (ddlDiscountPercentage.Text == "0")
        {
            txtFinalAnnualPremiumNoDisc.Enabled = false;
        }
        else
        {
            txtFinalAnnualPremiumNoDisc.Enabled = true;
        }
    }

    protected void chkCTPL_CheckedChanged(object sender, EventArgs e)
    {
        if (chkCTPL.Checked)
        {
            txtCTPL.Enabled = true;
            ddlVehicleBodyType.Enabled = true;
            ddlVehicleBodyType_SelectedIndexChanged(sender, e);
        }
        else
        {
            txtCTPL.Enabled = false;
            ddlVehicleBodyType.Enabled = false;
            txtGrossPremium_TextChanged(sender, e);
        }
    }

    protected void chkCompanyStaff_CheckedChanged(object sender, EventArgs e)
    {
        LoadDiscountPercentageList();

        if (chkCompanyStaff.Checked)
        {
            ListItem _lstTwelve = ddlDiscountPercentage.Items.FindByValue("12");
            if (_lstTwelve != null)
            {
                ddlDiscountPercentage.Text = "12";
            }
            ListItem _lstFifteen = ddlDiscountPercentage.Items.FindByValue("15");
            if (_lstFifteen != null)
            {
                ddlDiscountPercentage.Text = "15";
            }
            if (ddlBrokerProvider.Text == "41")
            {
                ddlDiscountPercentage.Text = "0";
            }
        }

        ddlDiscountPercentage_SelectedIndexChanged(sender, e);
    }

    protected void txtCTPL_TextChanged(object sender, EventArgs e)
    {
        txtGrossPremium_TextChanged(sender, e);
    }

    protected void chkConfirmEmail_CheckedChanged(object sender, EventArgs e)
    {
        txtConfirmEmail.Enabled = chkConfirmEmail.Checked;
        btnSendQuotation.Enabled = chkConfirmEmail.Checked;
    }

    protected void chkChangePremium_CheckedChanged(object sender, EventArgs e)
    {
        rfvPremiumChangeComments.Enabled = chkChangePremium.Checked;
        txtFinalAnnualPremiumNoDisc.ReadOnly = !chkChangePremium.Checked;
        txtFinalAnnualPremiumNoDisc.Enabled = chkChangePremium.Checked;
        txtFinalAnnualPremium.ReadOnly = !chkChangePremium.Checked;
        txtFinalAnnualPremium.Enabled = chkChangePremium.Checked;
        chkGetTesco.Enabled = !chkChangePremium.Checked;

        // re-calculate : get premium before change 
        // 15/5/2014
        if (chkChangePremium.Checked == false)
            txtGrossPremium_TextChanged(null, null);
    }

    protected void btnSendQuotation_Click(object sender, EventArgs e)
    {
        try
        {
            Int16 IsThai = 1;
            if (chkIsEN.Checked)
            {
                IsThai = 0;
            }

            if (IsThai == 1)
            {
                Session["Language"] = "th-TH";
            }
            else
            {
                Session["Language"] = "en-US";
            }

            String selectedCulture = CE.Global.General.SetCulture();
            base.InitializeCulture();

            NonGGPremiumListPDFOutput _nonGGPdf = CreateNonGGPDFObject();
            string _fileName = _nonGGPdf.GeneratePDF(Convert.ToString(Session["Language"]), chkIsPromotion.Checked);
            if (_fileName != string.Empty)
            {
                FileInfo file = new System.IO.FileInfo(_fileName);
                BrokerPremiumDB _premiumDB = new BrokerPremiumDB();

                if (file.Exists)
                {
                    string[] _file = new string[1];
                    _file[0] = _fileName;

                    string _toemail = txtConfirmEmail.Text.Trim().ToLower();
                    string _ccemail = string.Empty;//Session[General.UserEmail].ToString();
                    if (Session[General.UserRole].ToString() == "100")
                    {
                        _ccemail += Session[General.SMTPReplyTo].ToString();
                    }

                    string _bccemail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("ADMIN");
                    string _customerName = lblName.Text + " " + lblLastName.Text;
                    //string imgUrl = "http://" + CE.Configuration.MyConfigurationManager.GetAppSettingValue("LogoPath");
                    string imgUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("CRMPath") + "/";
                    string _emailTitle = string.Empty;
                    StringBuilder strMailBody = new StringBuilder();
                    strMailBody.Append(@"<html>
                        <head>
                        <meta charset='utf-8'>
                        <title>GluayGluay</title>
                        <style>
                        body {
	                        margin-left: 0px;
	                        margin-top: 0px;
	                        margin-right: 0px;
	                        margin-bottom: 0px;
	                        font-family: tahoma, Arial, sans-serif;
	                        font-size: 14px;
	                        color: #4F4356 ;
	                        background-repeat: repeat-x;
	                        background-color: #fff;
	                        text-decoration: none;
                        }
                        a:link  {text-decoration:none; color:#0674DB;}
                        hr{display: block; height: 1px;
                            border: 0; border-top: 1px solid #ccc;
                            margin: 1em 0; padding: 0;}
	                        .line-height{line-height:20px;}
	                        .table-txt{padding-left:5px;}
                        </style>
                        </head><body>
                        <div class='email-containter'>
                        <div class='email-banner'></div>
                        <div class='email-text'>
                        <table width='800' border='0' align='center' cellpadding='0' cellspacing='0'>
                        <tr>
                            <td height='653' align='right' valign='bottom' bgcolor='#FFFFFF'>
                            <table width='800' height='100' border='0' cellspacing='0' cellpadding='0'>");
                    strMailBody.Append("<tr><td><span class='email-banner'><img src='" + imgUrl + "images/email-header.jpg' width='800' height='100' alt=''/></span></td>");
                    strMailBody.Append(@"</tr>
                            </table>
                            <table width='800' border='0' align='center' cellpadding='0' cellspacing='0'>
                            <tr>
                                <td width='672' align='left' valign='top' bgcolor='#FFFFFF'>
                            <table border='0' cellspacing='0' cellpadding='0'>
                            <tr>
                            <td align='left'>");
                    string mailBody = strMailBody.ToString();
                    if (IsThai == 1)
                    {
                        // "Khun. " + _customerName + ", License Plate: " + txtLicensePlate.Text + " Quotation at " + DateTime.Now.ToString("dd/MMM/yyyy");
                        _emailTitle = "GluayGluay.com: ใบเสนอราคาประกันรถยนต์ คุณ " + lblName.Text + " " + txtEditLicensePlate.Text;
                        mailBody += @"<p>เรียน คุณ <strong>" + _customerName + "</strong><br/></p>" +
                        "<p style=\"text-align: justify\"><a href='http://www.gluaygluay.com'>GluayGluay.com</a> ขอส่งใบเสนอราคาแบบประกันรถยนต์ให้คุณ " + _customerName + " ได้ทำการเปรียบเทียบและตัดสินใจ<br/> " +
                        "หากท่านต้องการที่จะซื้อหรือต้องการสอบถามรายละเอียดเพิ่มเติม กรุณาติดต่อ <strong>" + Session[General.UserName] + "</strong> ได้ที่หมายเลขโทรศัพท์ <strong>" + Session[General.UserPhoneNo].ToString() + "</strong>";
                        mailBody += " ขอบพระคุณค่ะ <br/></p>";

                        mailBody += "</td></tr><tr><td align=\"left\">";
                        mailBody += "<br/>ขอแสดงความนับถือ<br/></td></tr></table><hr><p>" +
                        "<br/><strong><a href='http://www.gluaygluay.com'>GluayGluay.com</a> Support Team</strong><br/>" +
                            //Company Name changed
                        "บริษัท คอมแพร์เอ็กซ์เพรส นายหน้าประกันภัย (ประเทศไทย) จำกัด<br/>" +
                        "เลขทะเบียนนายหน้าประกันวินาศภัยนิติบุคคล เลขที่ ว00016/2553<br/>" +
                        "42nd Floor, United Center Building,<br/>" +
                        "323 Silom Road, Bangrak, Bangkok 10500</p>" +
                        "<p>โทร. 02-268-8222 <br>โทรสาร 02-266-6339<br/>" +
                        "<a href=\"mailto:support@gluaygluay.com\">support@gluaygluay.com</a></p></td>" +
                        "</tr></table><hr>";
                    }
                    else if (IsThai == 0)
                    {
                        _emailTitle = "Car Insurance quotation  from gluaygluay.com for " + lblName.Text + " " + txtEditLicensePlate.Text;
                        mailBody += @"<p>Dear <strong>" + _customerName + "</strong><br/></p>" +
                        "<p style=\"text-align: justify\"><a href='http://www.gluaygluay.com'>Gluaygluay.com</a> would like to send you the quotation of your car insurance for compare and consider " +
                        "If you would like to buy or would like to get any further information kindly contact <strong>" + Session[General.UserNameEN] + "</strong> at our hotline number <strong>" + Session[General.UserPhoneNoEN].ToString() + "</strong>, thank you very much.</p>";

                        mailBody += "</td></tr><tr><td align=\"left\">";
                        mailBody += "<br/>With best regards,<br/></td></tr></table><hr><p>" +
                        "<br/><strong><a href='http://www.gluaygluay.com'>Gluaygluay.com</a> Support Team</strong><br/>" +
                        "Comparexpress Insurance Broker ( Thailand ) Ltd,<br/>" +
                        "License number  ว00016/2553<br/>" +
                        "42nd Floor, United Center Building,<br/>" +
                        "323 Silom Road, Bangrak, Bangkok 10500</p>" +
                        "<p>Tel : 02-268-8222 , Fax : 02-266-6339<br/>" +
                        "<a href=\"mailto:support@gluaygluay.com\">support@gluaygluay.com</a></p></td>" +
                        "</tr></table><hr>";
                    }

                    string YearEn = dateTimeNow.Year.ToString();
                    strMailBody = new StringBuilder();
                    strMailBody.Append(@"<table width='300' border='0' align='center' cellpadding='0' cellspacing='0'><tr>");
                    strMailBody.Append("<td width='44' style='text-align: center'><a href='https://www.facebook.com/GGmotor'><img src='" + imgUrl + "images/icons/fb-big.png' width='44' height='42' alt=''/></a></td>");
                    strMailBody.Append("<td width='44' style='text-align: center'><a href='https://plus.google.com/+Gluaygluay/posts'><img src='" + imgUrl + "images/icons/g-plus-big.png' width='44' height='42' alt=''/></a></td>");
                    strMailBody.Append("<td width='44' style='text-align: center'><a href='https://www.youtube.com/channel/UCZ4gMtlXymBHxvcXO2cR1vA'><img src='" + imgUrl + "images/icons/youtube-big.png' width='44' height='42' alt=''/></a></td>");
                    strMailBody.Append("<td width='44' style='text-align: center'><a href='http://iconosquare.com/ggmotor'><img src='" + imgUrl + "images/icons/instagram-big.png' width='44' height='42' alt=''/></a></td>");
                    strMailBody.Append("<td width='43' style='text-align: center'><a href='https://www.linkedin.com/company/-com-gluaygluay-com-'><img src='" + imgUrl + "images/icons/linkedin-big.png' width='44' height='42' alt=''/></a></td>");
                    strMailBody.Append(@"</tr>
                                         </table>
                                         <table width='800' height='100' border='0' cellspacing='0' cellpadding='0' background='images/email-footer.jpg'>
                                            <tr>
                                              <td><p style='text-align: center'><br><br>
                                                © " + YearEn + " gluaygluay.com. All rights reserved.<br>");
                    strMailBody.Append(Resources.EmailMessage.NoReply);
                    strMailBody.Append(@"</p></td></tr>
                                          </table></td>
                                          </tr>
                                        </table>
                                        </body>
                                        </html>");
                    mailBody += strMailBody.ToString();

                    bool _mailSendingStatus = false;

                    if (Session[General.SMTPAccountName].ToString().Contains("gluaygluay.com"))
                    {
                        _mailSendingStatus = MyMailManager.SendGGMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString(), _file);
                    }
                    else if (Session[General.SMTPAccountName].ToString().Contains("comparexpress.co.th"))
                    {
                        _mailSendingStatus = MyMailManager.SendGGMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString(), _file);
                    }
                    else if (Session[General.SMTPAccountName].ToString().Contains("gmail.com"))
                    {
                        _mailSendingStatus = MyMailManager.SendGGMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString(), _file);
                    }
                    else
                    {
                        _mailSendingStatus = MyMailManager.SendCXMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString(), _file);
                    }

                    if (_mailSendingStatus)
                    {
                        if (_premiumDB.SaveQuotationEmail(Convert.ToInt32(txtCarId.Text),
                            Convert.ToInt64(txtCustomerId.Text),
                            Convert.ToInt64(Session[General.UserId].ToString()),
                            txtEditLicensePlate.Text,
                            txtConfirmEmail.Text, 1, _fileName) > 0)
                        {
                            lblSendQuotationMessage.Text = Resources.General.QuotationSent + " at " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm tt");
                        }
                        else
                        {
                            lblSendQuotationMessage.Text = Resources.General.QuotationSent + " Saving confirm email failed.";
                        }

                        chkConfirmEmail.Checked = false;
                        chkConfirmEmail_CheckedChanged(sender, e);
                        chkConfirmEmail.Enabled = false;
                    }
                    else
                    {
                        lblSendQuotationMessage.Text = Resources.General.QuotationFailed;
                    }
                }
                else
                {
                    lblSendQuotationMessage.Text = "PDF generating failed.";
                    lblSendQuotationMessage.Text += " " + Resources.General.QuotationFailed;
                }
            }
            else
            {
                lblSendQuotationMessage.Text = "PDF generating failed. No item found.";
                lblSendQuotationMessage.Text += " " + Resources.General.QuotationFailed;
            }

        }
        catch (Exception Ex)
        {

            lblSendQuotationMessage.Text = Ex.Message;
        }

        if (lblLangOption.Text == "1")
        {
            Session["Language"] = "th-TH";
        }
        else
        {
            Session["Language"] = "en-US";
        }

        CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    #region Get Car Detail

    protected void GetCarDetailList()
    {
        CE.Database.MyDatabase _db = new CE.Database.MyDatabase();
        SortedList paraList = new SortedList();
        paraList.Add("@CustomerID", txtCustomerId.Text) ;
        paraList.Add("@CarId", txtCarId.Text);
        paraList.Add("@AgentID", txtAgentId.Text);
        DataTable _dt = _db.GetDataTableBySP("sprocCXCRMGetCarDetailListByCustomerID", paraList);

        if (_dt != null)
        {
            DataRow _dr = _dt.Rows[0];
            lblCarDtlCarID.Text = _dr["CarID"].ToString();
            lblCarDtlCarPolicyID.Text = _dr["CECarPolicyID"].ToString();
            lblCarDtlCarMakeModel.Text = _dr["MakeModelDesc"].ToString();
            lblCarDtlCarModelYear.Text = _dr["ManufactYear"].ToString();
            lblCarDtlInsuranceType.Text = _dr["InsuranceTypeDesc"].ToString();
            lblCarDtlNCB.Text = _dr["NCDPercentDesc"].ToString();

            if (_dr["CoverageCommenceDate"] != DBNull.Value)
                lblCarDtlComDate.Text = Convert.ToDateTime(_dr["CoverageCommenceDate"]).ToString("dd-MMM-yyyy");
            if (_dr["ModifiedDate"] != DBNull.Value)
                lblCarDtlModifiedDate.Text = Convert.ToDateTime(_dr["ModifiedDate"]).ToString("dd-MMM-yyyy hh:mm tt");
        }
        ResetAll();
        ShowCarAndCustomerDetails(Convert.ToInt64(txtCustomerId.Text), Convert.ToInt64(lblCarDtlCarID.Text), Convert.ToInt64(lblCarDtlCarPolicyID.Text));
        divCustomerPolicyDetail.Focus();
    }

    #endregion

    #region Excel Result

    private void GetTempResultExcelOne()
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dtResult = new DataTable();
        string _spName = "[sprocCarInsurancePremiumSelectItemListExcel]";
        SortedList _sPara = new SortedList();

        _sPara.Add("@CarId", txtCarId.Text);
        if (Convert.ToInt64(txtAgentId.Text) > 0)
        {
            _sPara.Add("@AgentId", Convert.ToInt64(txtAgentId.Text));
        }
        else
        {
            _sPara.Add("@AgentId", 0);
        }

        _dtResult = _db.GetDataTableBySP(_spName, _sPara);

        
        //if (Session[General.UserId] != null)
        //{
        //    Cache["CarResultExcel" + Session[General.UserId].ToString() + txtCarId.Text] = _dtResult;
        //}
        //else
        //{
        //    Cache["CarResultExcel" + txtCarId.Text] = _dtResult;
        //}
        DataView _dvResult = new DataView();
        _dvResult = _dtResult.DefaultView;
        //if (_dtResult.Rows.Count > 0 && ddlQueryGarageType.SelectedValue != "-1")
        //{
        //    _dvResult.RowFilter = "GarageType = '" + ddlQueryGarageType.SelectedValue + "' OR GarageType IS NULL";
        //}

        gvCarResultExcel.DataSource = _dvResult;
        gvCarResultExcel.DataBind();
    }

    private void GetTempResultExcelTwo()
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dtResult = new DataTable();
        string _spName = "[sprocCarInsuranceResultCallMeSelectItemListExcel]";
        SortedList _sPara = new SortedList();

        _sPara.Add("@CarId", txtCarId.Text);
        if (Convert.ToInt64(txtAgentId.Text) > 0)
        {
            _sPara.Add("@AgentId", Convert.ToInt64(txtAgentId.Text));
        }
        else
        {
            _sPara.Add("@AgentId", 0);
        }
        _dtResult = _db.GetDataTableBySP(_spName, _sPara);

        if (Session[General.UserId] != null)
        {
            Cache["CarResultExcel" + Session[General.UserId].ToString() + txtCarId.Text] = _dtResult;
        }
        else
        {
            Cache["CarResultExcel" + txtCarId.Text] = _dtResult;
        }

    }

    protected void gvCarResultExcel_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        #region Not Use
//        if (e.CommandName.Equals("BuyNow"))
//        {
//            if (lblCommenceDateStatus.Text == "1" && lblQuoteDateTimeStatus.Text == "1")
//            {
//                int index = Convert.ToInt32(e.CommandArgument);
//                DataKey myData = gvCarResultExcel.DataKeys[index];

//                Session[CE.Global.General.CarResultId] = myData[0].ToString();
//                Session[CE.Global.General.ProviderCompanyId] = myData[1].ToString();
//                Int64 _resultId = Convert.ToInt64(myData[0].ToString());
//                Int64 _companyId = Convert.ToInt64(myData[1].ToString());

//                Session[General.CallPageStartDateTime] = lblStartDateTime.Text;
//                Session[General.BuyNowCarID] = txtCarId.Text;
//                divCarDetailList.Visible = false;

//                string _buyurl = myData[2].ToString();
//                string proposalURL = CE.Configuration.MyConfigurationManager.GetAppSettingValue("CIServerPath");

//                proposalURL = proposalURL + "agentlogin.aspx?" + _buyurl;
//                ClientScript.RegisterClientScriptBlock(this.GetType(), "OpenBuyNow", "var myRef = window.open('" + proposalURL + "','mywin','left=20,top=20,width=800,height=600,resizable=1,scrollbars=1');", true);
//                divBuyNowStatus.Visible = true;
//                //divResult.Visible = false;
//                divCallStatus.Visible = false;
//                //08/07/2013 Wam's Excel
//                divResultExcel.Visible = false;

//                //hplReRunQuote.Enabled = false;
//                //hplNewQuote.Enabled = false;
//                //divLinks.Visible = false;

//                MyDatabase _db = new MyDatabase();
//                DataTable _dt = new DataTable("tblSelectedItem");

//                string _sqlQ = @"Select top 10 pc.CompanyName, t.AnnualPremium, t.CoverTypeDesc from tblCarInsuranceTempExcelResultTH t 
//	            INNER JOIN tblProviderCompany pc ON t.ProviderCompanyId = pc.ProviderCompanyId 
//	            WHERE t.CITempResultId = " + myData[0].ToString();
//                _dt = _db.GetDataTable(_sqlQ);

//                lblBuyNowStatus.Text = Resources.General.BUYONLINEClickMessage + "<br/>" + Resources.General.CheckAndRefreshMessage;
//                if (_dt != null && _dt.Rows.Count > 0)
//                {
//                    divBuyNowStatusMessage.Visible = true;
//                    System.Text.StringBuilder _strBuilder = new System.Text.StringBuilder();
//                    _strBuilder.Append("<br/><br/><table width='50%' cellspacing='5' cellpadding='5'>");
//                    _strBuilder.Append("<tr><td>" + Resources.CarInsurance.CompanyName + "</td><td>:</td><td><b>" + _dt.Rows[0]["CompanyName"].ToString() + "</b></td></tr>");
//                    _strBuilder.Append("<tr><td>" + Resources.General.PremiumAmount + "</td><td>:</td><td><b>" + Convert.ToDouble(_dt.Rows[0]["AnnualPremium"].ToString()).ToString("#,000.00") + "</b></td></tr>");
//                    _strBuilder.Append("<tr><td>" + Resources.General.PackageName + "</td><td>:</td><td><b>" + _dt.Rows[0]["CoverTypeDesc"].ToString() + "</b></td></tr>");
//                    _strBuilder.Append("</table>");
//                    lblBuyNowStatus.Text += _strBuilder.ToString();
//                }
//            }
//            else
//            {

//                ShowQuoteStatusAlert();
//            }
//        }
//        else 
        #endregion
        if (e.CommandName.Equals("Select"))
        {
            int index = Convert.ToInt32(e.CommandArgument);
            DataKey myData = gvCarResultExcel.DataKeys[index];

            Int64 _resultId = Convert.ToInt64(myData[0].ToString());
            //Int64 _companyId = Convert.ToInt64(myData[1].ToString());
            PremiumSelectedIndexChangedExcel(_resultId);

            ddlBrokerProvider.Enabled = true;

            //ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "scrollToQuote();", true);
        }
    }

    protected void gvCarResultExcel_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            foreach (TableCell cell in e.Row.Cells)
            {
                if (cell.HasControls())
                {
                    LinkButton button = cell.Controls[0] as LinkButton;
                    if (button != null)
                    {
                        Image imageSort = new Image();
                        imageSort.ImageUrl = "~/OLD/images/icons/clear.gif";
                        HtmlGenericControl gv = new HtmlGenericControl("div");
                        Label lnkName = new Label();
                        lnkName.Text = button.Text;

                        if (ViewState["SortExpression"] != null && ViewState["SortExpression"].ToString() == button.CommandArgument.ToString())
                        {
                            if (ViewState["SortOrder"] != null && ViewState["SortOrder"].ToString() == SortDirection.Descending.ToString())
                            {
                                imageSort.ImageUrl = "~/OLD/images/icons/Sort_Down.gif";
                            }
                            else
                            {
                                imageSort.ImageUrl = "~/OLD/images/icons/Sort_Up.gif";
                            }
                        }
                        gv.Controls.Add(lnkName);
                        gv.Controls.Add(imageSort);
                        button.Controls.Add(gv);
                    }
                }
            }

            //Creat Custome Header
            GridView HeaderGrid = (GridView)sender;
            GridViewRow HeaderGridRow =
            new GridViewRow(0, 0, DataControlRowType.Header,
            DataControlRowState.Insert);

            TableCell HeaderCell = new TableCell();
            HeaderCell.Text = "";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.ColumnSpan = 3;
            HeaderGridRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "<img src='../../images/arrows/arrow-down.png\'  />" + Resources.CarInsuranceResultPage.OwnDamage + "<img src=\"../../images/arrows/arrow-down.png\" align=\"absmiddle\" alt=\"\" />";
            HeaderCell.Font.Bold = true;
            HeaderCell.ControlStyle.CssClass = "green_top";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.ColumnSpan = 2;
            HeaderGridRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "<img src=\"../../images/arrows/arrow-down.png\" align=\"absmiddle\" alt=\"\" /> " + Resources.CarInsuranceResultPage.ThirdPartyLiability + "<img src=\"../../images/arrows/arrow-down.png\" align=\"absmiddle\" alt=\"\" /><br/>" + Resources.CarInsuranceResultPage.PerAccident;
            HeaderCell.Font.Bold = true;
            HeaderCell.ControlStyle.CssClass = "blue_top";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.ColumnSpan = 3;
            HeaderGridRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "<img src=\"../../images/arrows/arrow-down.png\" align=\"absmiddle\" alt=\"\" />" + Resources.CarInsuranceResultPage.AdditionalCovers + "<img src=\"../../images/arrows/arrow-down.png\" align=\"absmiddle\" alt=\"\" />";
            HeaderCell.Font.Bold = true;
            HeaderCell.ControlStyle.CssClass = "gold_top";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.ColumnSpan = 3;
            HeaderGridRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;

            HeaderGridRow.Cells.Add(HeaderCell);

            gvCarResultExcel.Controls[0].Controls.AddAt
            (0, HeaderGridRow);
        }

        //if (e.Row.RowType == DataControlRowType.DataRow)
        //{
        //    ImageButton ibtBuyNow = (ImageButton)e.Row.FindControl("ibtBuyNow");
        //    ibtBuyNow.CommandArgument = e.Row.RowIndex.ToString();
        //    HyperLink _lnkTest = new HyperLink();
        //    ibtBuyNow.OnClientClick = "javascript:return confirm('" + Resources.General.ConfirmBUYONLINEMessage + "');";
        //    _lnkTest = null;
        //}
    }

    protected void gvCarResultExcel_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //HIDE
        //For Thailand
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string _callCarProviderId = "";

            string _companyId = DataBinder.Eval(e.Row.DataItem, "ProviderCompanyId").ToString();
            _callCarProviderId = _companyId;

            //Company Logo and Cover Type
            //Label lblCoverTypeDesc = (Label)e.Row.FindControl("lblPackageName");
            Image imgCompanyLogo = (Image)e.Row.FindControl("imgCompanyLogo");
            string _logoUrl = DataBinder.Eval(e.Row.DataItem, "CompanyLogoServerUrl").ToString();
            imgCompanyLogo.ImageUrl = "~" + _logoUrl;

            ////CTPL
            Label lblCTPL = (Label)e.Row.FindControl("lblCTPL");
            Label lblCTPLSymbol = (Label)e.Row.FindControl("lblCTPLSymbol");
            Image imgCTPL = (Image)e.Row.FindControl("imgCTPL");
            string _totalCMI = DataBinder.Eval(e.Row.DataItem, "TotalCMI").ToString().Trim();

            if (_totalCMI != null && _totalCMI != string.Empty && Convert.ToSingle(_totalCMI) > 0.0f)
            {
                imgCTPL.Visible = false;
                lblCTPL.Text = _totalCMI;
                lblCTPL.Visible = true;
                lblCTPLSymbol.Visible = true;
            }
            else
            {
                imgCTPL.Visible = true;
                lblCTPL.Text = "0";
                lblCTPL.Visible = false;
                lblCTPLSymbol.Visible = false;
            }
            ////END CTPL

            // Garage
            Label lblExcelGarage = (Label)e.Row.FindControl("lblExcelGarage");
            string _garagetype = DataBinder.Eval(e.Row.DataItem, "GarageType").ToString().Trim();
            if (_garagetype == "1")
            {
                lblExcelGarage.Text = Resources.CarInsurance.Garage_Authorized;
            }
            else if (_garagetype == "2")
            {
                lblExcelGarage.Text = Resources.CarInsurance.Garage_Dealer;
            }
            else
            {
                lblExcelGarage.Text = "";
            }

            //// DEC
            Label lblDEC = (Label)e.Row.FindControl("lblDEC");
            Label lblDECSymbol = (Label)e.Row.FindControl("lblDECSymbol");
            Label lblDECZero = (Label)e.Row.FindControl("lblDECZero");
            string _DEC = DataBinder.Eval(e.Row.DataItem, "DEC").ToString().Trim();

            if (_DEC != null && _DEC != string.Empty && Convert.ToSingle(_DEC) > 0.0f)
            {
                lblDECZero.Visible = false;
                lblDEC.Text = _DEC;
                lblDEC.Visible = true;
                lblDECSymbol.Visible = true;
            }
            else
            {
                lblDECZero.Visible = true;
                lblDEC.Text = "0";
                lblDEC.Visible = false;
                lblDECSymbol.Visible = false;
            }
            //// END DEC

            ///SUM INSURED OR OWN DAMAGE FIRE OR THIEF
            Label lblSumInsured = (Label)e.Row.FindControl("lblSumInsured");
            Label lblSumInsuredSymbol = (Label)e.Row.FindControl("lblSumInsuredSymbol");
            Image imgSumInsured = (Image)e.Row.FindControl("imgSumInsured");
            string _sumInsured = DataBinder.Eval(e.Row.DataItem, "SumInsured").ToString().Trim();

            if (_sumInsured != null && _sumInsured != string.Empty && Convert.ToSingle(_sumInsured) > 0.0f)
            {
                imgSumInsured.Visible = false;
                lblSumInsured.Text = Convert.ToInt32(_sumInsured).ToString("#,000"); //_sumInsured;
                lblSumInsured.Visible = true;
                lblSumInsuredSymbol.Visible = true;
            }
            else
            {
                imgSumInsured.Visible = true;
                lblSumInsured.Text = "0";
                lblSumInsured.Visible = false;
                lblSumInsuredSymbol.Visible = false;
            }
            ///END SUM INSURED OR OWN DAMAGE FIRE OR THIEF

            //Flood
            string _flood = DataBinder.Eval(e.Row.DataItem, "Flood").ToString().Trim();
            if (_flood != null && _flood != string.Empty && Convert.ToSingle(_flood) > 0.0f)
            {
                Label lblFloodCover = (Label)e.Row.FindControl("lblFloodCover");
                lblFloodCover.Text = Resources.CarInsuranceResultPage.FloodCover;
            }

            //HyperLink hplnkWorkshop = new HyperLink();
            HyperLink hplnkWorkshop = (HyperLink)e.Row.FindControl("hplWorkshopLink");
            hplnkWorkshop.Target = "_blank";
            hplnkWorkshop.Font.Bold = true;
            if (_companyId == "11")
            {
                // "Allianz C.P";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AllianceWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AllianceWorkshopEN");
                }

            }
            else if (_companyId == "12")
            {
                //lblPromo.Text = "MSIG";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MSIGWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MSIGWorkshopEN");
                }
            }
            else if (_companyId == "16")
            {
                //lblPromo.Text = "AXA";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AXAWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AXAWorkshopEN");
                }
            }
            else if (_companyId == "29")
            {
                //lblPromo.Text = "LMG Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LMGWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LMGWorkshopEN");
                }
            }
            else if (_companyId == "31")
            {
                //lblPromo.Text = "Chartis";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ChartisWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ChartisWorkshopEN");
                }
            }
            else if (_companyId == "32")
            {
                //lblPromo.Text = "Bangkok Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.BKIWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.BKIWorkshopEN");
                }
            }
            else if (_companyId == "33")
            {
                //lblPromo.Text = "MTI Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MTIWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MTIWorkshopEN");
                }
            }
            else if (_companyId == "35")
            {
                //lblPromo.Text = "KPI Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.KPIWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.KPIWorkshopTH");
                }
            }
            else if (_companyId == "39")
            {
                //lblPromo.Text = "KPI Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MittareWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MittareWorkshopEN");
                }
            }
            else if (_companyId == "41")
            {
                //lblPromo.Text = "Kurnia Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.KurniaWorkShopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.KurniaWorkShopTH");
                }
            }
            else if (_companyId == "43")
            {
                //lblPromo.Text = "SMK Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.SMKWorkShopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.SMKWorkShopEN");
                }
            }
            else if (_companyId == "45")
            {
                //lblPromo.Text = "Viriyah Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ViriyahWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ViriyahWorkshopEN");
                }
            }
            else if (_companyId == "46")
            {
                //lblPromo.Text = "TMS Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.TokioWorkShopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.TokioWorkShopEN");
                }
            }
            else if (_companyId == "58")
            {
                //lblPromo.Text = "ThaiVivat Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ThaivivatWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ThaivivatWorkshopEN");
                }
            }
            else if (_companyId == "66")
            {
                //lblPromo.Text = "Dhipaya Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.DhipayaWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.DhipayaWorkshopEN");
                }
            }
            else if (_companyId == "67")
            {
                //lblPromo.Text = "Deves Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.DevesWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.DevesWorkshopEN");
                }
            }
            else if (_companyId == "68")
            {
                //lblPromo.Text = "Thaisri Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ThaiSriWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ThaiSriWorkshopEN");
                }
            }
            else if (_companyId == "69")
            {
                //lblPromo.Text = "Thaisri Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AssetsWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AssetsWorkshopEN");
                }
            }
            //END GARAGE
        }

    }

    private void PremiumSelectedIndexChangedExcel(Int64 ResultId)
    {
        MyDatabase _myDb = new MyDatabase();
        DataTable _dtSeletedItem = new DataTable("tblSelect");
        _dtSeletedItem = _myDb.GetDataTable(@"SELECT T.[PremiumExcelId]
		  ,T.[ProviderCompanyId]
		  ,T.PackageName
		  ,T.[Premium]
		  ,dbo.fn_getPromotionPriceCRM(T.[ProviderCompanyId], T.[Premium]) AS PromotionPrice
		  ,CASE WHEN T.VehicleCode = 320 THEN 967.28 ELSE 645.21 END AS TotalCMI
		  ,T.[TPPD]
		  ,T.[TPBIP]
		  ,T.[TPBIA]
		  ,T.[DEC]
		  ,T.[SumInsured]
		  ,T.[FireAndTheft]
		  ,T.Flood
		  ,T.[PAPassenger] AS PADriver
		  ,T.[PAPassenger]
		  ,T.[MedicalExpense]
		  ,T.[BailBond]
		  ,T.Seat 
		  ,T.GarageType
		  ,T.IsEuropeCar
		  ,T.TypeOfPlan
		  ,T.VehicleCode	  
		FROM tblPremiumExcel T
	    Where T.PremiumExcelId = " + ResultId.ToString());

        if (_dtSeletedItem != null && _dtSeletedItem.Rows.Count > 0)
        {
            btnNewPremium_Click(null, null);

            ddlBrokerProvider.SelectedIndex = ddlBrokerProvider.Items.IndexOf(ddlBrokerProvider.Items.FindByValue(_dtSeletedItem.Rows[0]["ProviderCompanyId"].ToString()));
            ddlBrokerProvider_SelectedIndexChanged(null, null);
            ddlBrokerCoverType.Text = _dtSeletedItem.Rows[0]["TypeOfPlan"].ToString();
            //Yui@22/01/2015
            chkMile.Checked = false;
            if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11")
                chkMile.Enabled = true;
            else
                chkMile.Enabled = false;

            if (txtPremiumId.Text == "0")
            {
                ddlGarageType.Text = _dtSeletedItem.Rows[0]["GarageType"].ToString();

                if (_dtSeletedItem.Rows[0]["TPBIA"] != DBNull.Value)
                {
                    txtTPBIA.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPBIA"].ToString()).ToString("#,000");
                }
                else
                {
                    txtTPBIA.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["TPBIP"] != DBNull.Value)
                {
                    txtTPBIP.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPBIP"].ToString()).ToString("#,000");
                }
                else
                {
                    txtTPBIP.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["TPPD"] != DBNull.Value)
                {
                    txtTPPD.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPPD"].ToString()).ToString("#,000");
                }
                else
                {
                    txtTPPD.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["DEC"] != DBNull.Value)
                {
                    txtDeductible.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["DEC"].ToString()).ToString("#0");
                }

                if (_dtSeletedItem.Rows[0]["PAPassenger"] != DBNull.Value)
                {
                    txtPA.Text = _dtSeletedItem.Rows[0]["PAPassenger"].ToString();
                }
                else
                {
                    txtPA.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["BailBond"] != DBNull.Value)
                {
                    txtBailBond.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["BailBond"].ToString()).ToString("#,000");
                }
                else
                {
                    txtBailBond.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["FireAndTheft"] != DBNull.Value)
                {
                    txtFireTheft.Text = "0";
                    if (Convert.ToSingle(_dtSeletedItem.Rows[0]["FireAndTheft"].ToString()) > 0)
                    {
                        txtFireTheft.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["FireAndTheft"].ToString()).ToString("#,000");
                    }
                }
                else
                {
                    txtFireTheft.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["MedicalExpense"] != DBNull.Value)
                {
                    txtMED.Text = _dtSeletedItem.Rows[0]["MedicalExpense"].ToString();
                }
                else
                {
                    txtMED.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["SumInsured"] != DBNull.Value)
                {
                    txtOwnDamage.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["SumInsured"].ToString()).ToString("#,000");
                }
                else
                {
                    txtOwnDamage.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["Flood"] != DBNull.Value)
                {
                    txtFloodCoverAmount.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["Flood"].ToString()).ToString("#,000");
                }
                else
                {
                    txtFloodCoverAmount.Text = "N/A";
                }

                txtGrossPremium.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["Premium"].ToString()).ToString(); //"#,000"

                float _totalCMI = 0.0f;
                if (_dtSeletedItem.Rows[0]["TotalCMI"] != DBNull.Value)
                {
                    _totalCMI = Convert.ToSingle(_dtSeletedItem.Rows[0]["TotalCMI"].ToString());
                }
                chkCTPL.Checked = false;

                txtCTPL.Text = _totalCMI.ToString("#,000.00");

                txtGrossPremium_TextChanged(null, null);
            }
        }
    }

    private void PremiumSelectedFromExcel(Int64 ResultId)
    {
        MyDatabase _myDb = new MyDatabase();
        DataTable _dtSeletedItem = new DataTable("tblSelect");
        _dtSeletedItem = _myDb.GetDataTable(@"SELECT CITempResultId,
			ProviderCompanyId,
			CoverTypeDesc,
			AnnualPremium Premium,
			PromotionPrice,
			TotalCMI,
			TPPD,
			TPBIP,
			TPBIA,
			DEC,
			SumInsured,
			Fire FireAndTheft,
			Ninfo6 AS Flood,
			PADriver,
			PAPassenger,
			MedicalExpense,
			BailBond,
			info3 AS GarageType,
			Info1 TypeOfPlan
			FROM tblCarInsuranceTempExcelResultTH
	        Where CITempResultId = " + ResultId.ToString());

        if (_dtSeletedItem != null && _dtSeletedItem.Rows.Count > 0)
        {
            btnNewPremium_Click(null, null);

            ddlBrokerProvider.SelectedIndex = ddlBrokerProvider.Items.IndexOf(ddlBrokerProvider.Items.FindByValue(_dtSeletedItem.Rows[0]["ProviderCompanyId"].ToString()));
            ddlBrokerProvider_SelectedIndexChanged(null, null);
            ddlBrokerCoverType.Text = _dtSeletedItem.Rows[0]["TypeOfPlan"].ToString();
            //Yui@22/01/2015
            chkMile.Checked = false;
            if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11")
                chkMile.Enabled = true;
            else
                chkMile.Enabled = false;

            if (txtPremiumId.Text == "0")
            {
                ddlGarageType.Text = _dtSeletedItem.Rows[0]["GarageType"].ToString();

                if (_dtSeletedItem.Rows[0]["TPBIA"] != DBNull.Value)
                {
                    txtTPBIA.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPBIA"].ToString()).ToString("#,000");
                }
                else
                {
                    txtTPBIA.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["TPBIP"] != DBNull.Value)
                {
                    txtTPBIP.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPBIP"].ToString()).ToString("#,000");
                }
                else
                {
                    txtTPBIP.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["TPPD"] != DBNull.Value)
                {
                    txtTPPD.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPPD"].ToString()).ToString("#,000");
                }
                else
                {
                    txtTPPD.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["DEC"] != DBNull.Value)
                {
                    txtDeductible.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["DEC"].ToString()).ToString("#0");
                }

                if (_dtSeletedItem.Rows[0]["PAPassenger"] != DBNull.Value)
                {
                    txtPA.Text = _dtSeletedItem.Rows[0]["PAPassenger"].ToString();
                }
                else
                {
                    txtPA.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["BailBond"] != DBNull.Value)
                {
                    txtBailBond.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["BailBond"].ToString()).ToString("#,000");
                }
                else
                {
                    txtBailBond.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["FireAndTheft"] != DBNull.Value)
                {
                    txtFireTheft.Text = "0";
                    if (Convert.ToSingle(_dtSeletedItem.Rows[0]["FireAndTheft"].ToString()) > 0)
                    {
                        txtFireTheft.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["FireAndTheft"].ToString()).ToString("#,000");
                    }
                }
                else
                {
                    txtFireTheft.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["MedicalExpense"] != DBNull.Value)
                {
                    txtMED.Text = _dtSeletedItem.Rows[0]["MedicalExpense"].ToString();
                }
                else
                {
                    txtMED.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["SumInsured"] != DBNull.Value)
                {
                    txtOwnDamage.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["SumInsured"].ToString()).ToString("#,000");
                }
                else
                {
                    txtOwnDamage.Text = "N/A";
                }

                if (_dtSeletedItem.Rows[0]["Flood"] != DBNull.Value)
                {
                    txtFloodCoverAmount.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["Flood"].ToString()).ToString("#,000");
                }
                else
                {
                    txtFloodCoverAmount.Text = "N/A";
                }

                txtGrossPremium.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["Premium"].ToString()).ToString(); //"#,000"

                float _totalCMI = 0.0f;
                if (_dtSeletedItem.Rows[0]["TotalCMI"] != DBNull.Value)
                {
                    _totalCMI = Convert.ToSingle(_dtSeletedItem.Rows[0]["TotalCMI"].ToString());
                }
                chkCTPL.Checked = false;

                txtCTPL.Text = _totalCMI.ToString("#,000.00");

                txtGrossPremium_TextChanged(null, null);
            }
        }
    }

    //Yui@5/2/2015
    //<asp:UpdateProgress AssociatedUpdatePanelID="uplCarResultExcelQuery" DisplayAfter="50"
    //   runat="server" ID="upgSearchGarageType">
    //   <ProgressTemplate>
    //   &nbsp;&nbsp;&nbsp;&nbsp;<img src="../../images/loaders/loader2.gif" style="text-align: center"
    //   alt="Loading..." />
    //   </ProgressTemplate>
    //</asp:UpdateProgress>
    //OnSelectedIndexChanged="ddlQueryGarageType_SelectedIndexChanged"
    //protected void ddlQueryGarageType_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    FilterResultExcel();
    //}
    //private void FilterResultExcel()
    //{
    //    DataView dv = new DataView();
    //    if (Session[General.UserId] != null)
    //    {
    //        if (Cache["CarResultExcel" + Session[General.UserId].ToString() + txtCarId.Text] != null)
    //        {
    //            dv = new DataView((DataTable)Cache["CarResultExcel" + Session[General.UserId].ToString() + txtCarId.Text]);
    //        }
    //        else
    //        {
    //            GetTempResultExcelTwo();
    //            if (Session[General.UserId] != null)
    //            {
    //                dv = new DataView((DataTable)Cache["CarResultExcel" + Session[General.UserId].ToString() + txtCarId.Text]);
    //            }
    //            else
    //            {
    //                dv = new DataView((DataTable)Cache["CarResultExcel" + txtCarId.Text]);
    //            }
    //        }
    //    }
    //    else
    //    {
    //        if (Cache["CarResultExcel" + txtCarId.Text] != null)
    //        {
    //            dv = new DataView((DataTable)Cache["CarResultExcel" + txtCarId.Text]);
    //        }
    //        else
    //        {
    //            GetTempResultExcelTwo();
    //            if (Session[General.UserId] != null)
    //            {
    //                dv = new DataView((DataTable)Cache["CarResultExcel" + Session[General.UserId].ToString() + txtCarId.Text]);
    //            }
    //            else
    //            {
    //                dv = new DataView((DataTable)Cache["CarResultExcel" + txtCarId.Text]);
    //            }
    //        }
    //    }
    //    if (dv != null)
    //    {
    //        if (ddlQueryGarageType.SelectedValue != "-1")
    //        {
    //            dv.RowFilter = "GarageType = '" + ddlQueryGarageType.SelectedValue + "' OR GarageType IS NULL";
    //        }
    //        gvCarResultExcel.DataSource = dv;
    //    }
    //    else
    //    {
    //        gvCarResultExcel.DataSource = null;
    //    }
    //    gvCarResultExcel.DataBind();
    //}
    //************

//Yui@5/2/2015
//    private void CarResultSelectedIndexChangedExcel(Int64 CarResultId, Int64 ProviderCompanyId)
//    {
//        MyDatabase _myDb = new MyDatabase();
//        DataTable _dtSeletedItem = new DataTable("tblSelect");
//        _dtSeletedItem = _myDb.GetDataTable(@"SELECT P.INSURANCETYPE, P.GarageType, P.IsCTPL, 
//                                                    SPL = CASE WHEN T.Info1 IS NOT NULL AND T.Info1 = 'GGSPECIAL' THEN 'GGSPECIAL' ELSE 'PROVIDER' END,T.* 
//                                                    FROM tblCarInsuranceTempExcelResultTH T
//	                                                INNER JOIN tblCarPolicy P ON T.CARID = P.CECARID AND P.REFCEUSERID = T.REFCEUSERID 
//                                                    Where T.CarID = " + txtCarId.Text + " And T.RefCEUserID = " + txtCustomerId.Text + " And T.CITempResultID = " + CarResultId.ToString() + " And T.ProviderCompanyID = " + ProviderCompanyId.ToString());

//        if (_dtSeletedItem != null && _dtSeletedItem.Rows.Count > 0)
//        {
//            btnNewPremium_Click(null, null);
//            float _totalVMI = Convert.ToSingle(_dtSeletedItem.Rows[0]["TotalVMI"].ToString());
//            txtGG.Text = _dtSeletedItem.Rows[0]["SPL"].ToString();
//            if (txtGG.Text.Trim() == "GGSPECIAL")
//            {
//                DataTable _dtBrokerProvider = General.GetComboItem("BrokerProvider", "CXBrokerProviderId", ProviderCompanyId.ToString(), true);
//                if (_dtBrokerProvider != null && _dtBrokerProvider.Rows.Count > 0)
//                {
//                    ddlBrokerProvider.Items.Clear();
//                    ddlBrokerProvider.DataSource = _dtBrokerProvider;
//                    ddlBrokerProvider.DataTextField = _dtBrokerProvider.Columns[0].ColumnName.ToString();
//                    ddlBrokerProvider.DataValueField = _dtBrokerProvider.Columns[1].ColumnName.ToString();
//                    ddlBrokerProvider.DataBind();
//                    ddlBrokerProvider.Items.Insert(0, new ListItem("Select", "-1"));
//                }
//            }
            
//            ddlBrokerProvider.SelectedIndex = ddlBrokerProvider.Items.IndexOf(ddlBrokerProvider.Items.FindByValue(ProviderCompanyId.ToString()));
//            ddlBrokerProvider_SelectedIndexChanged(null, null);
//            ddlBrokerCoverType.Text = _dtSeletedItem.Rows[0]["INSURANCETYPE"].ToString();
//            //Yui@22/01/2015
//            chkMile.Checked = false;
//            if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11")
//                chkMile.Enabled = true;
//            else
//                chkMile.Enabled = false;

//            if (txtPremiumId.Text == "0")
//            {
//                ddlGarageType.Text = _dtSeletedItem.Rows[0]["GarageType"].ToString();


//                if (_dtSeletedItem.Rows[0]["TPBIA"] != DBNull.Value)
//                {
//                    txtTPBIA.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPBIA"].ToString()).ToString("#,000");
//                }
//                else
//                {
//                    txtTPBIA.Text = "N/A";
//                }

//                if (_dtSeletedItem.Rows[0]["TPBIP"] != DBNull.Value)
//                {
//                    txtTPBIP.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPBIP"].ToString()).ToString("#,000");
//                }
//                else
//                {
//                    txtTPBIP.Text = "N/A";
//                }

//                if (_dtSeletedItem.Rows[0]["TPPD"] != DBNull.Value)
//                {
//                    txtTPPD.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["TPPD"].ToString()).ToString("#,000");
//                }
//                else
//                {
//                    txtTPPD.Text = "N/A";
//                }

//                if (_dtSeletedItem.Rows[0]["DEC"] != DBNull.Value)
//                {
//                    txtDeductible.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["DEC"].ToString()).ToString("#0");
//                }

//                if (_dtSeletedItem.Rows[0]["PADriver"] != DBNull.Value)
//                {
//                    txtPA.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["PADriver"].ToString()).ToString("#,000");
//                }
//                else
//                {
//                    txtPA.Text = "N/A";
//                }

//                if (_dtSeletedItem.Rows[0]["BailBond"] != DBNull.Value)
//                {
//                    txtBailBond.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["BailBond"].ToString()).ToString("#,000");
//                }
//                else
//                {
//                    txtBailBond.Text = "N/A";
//                }

//                if (_dtSeletedItem.Rows[0]["Fire"] != DBNull.Value)
//                {
//                    txtFireTheft.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["Fire"].ToString()).ToString("#,000");
//                }
//                else
//                {
//                    txtFireTheft.Text = "N/A";
//                }

//                if (_dtSeletedItem.Rows[0]["MedicalExpense"] != DBNull.Value)
//                {
//                    txtMED.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["MedicalExpense"].ToString()).ToString("#,000");
//                }
//                else
//                {
//                    txtMED.Text = "N/A";
//                }

//                if (_dtSeletedItem.Rows[0]["SumInsured"] != DBNull.Value)
//                {
//                    txtOwnDamage.Text = Convert.ToSingle(_dtSeletedItem.Rows[0]["SumInsured"].ToString()).ToString("#,000");
//                }
//                else
//                {
//                    txtOwnDamage.Text = "N/A";
//                }

//                if (_dtSeletedItem.Rows[0]["IsFloodCover"] != DBNull.Value)
//                {
//                    if (_dtSeletedItem.Rows[0]["IsFloodCover"].ToString() == "1")
//                    {
//                        txtFloodCoverAmount.Text = txtOwnDamage.Text;
//                    }
//                    else
//                    {
//                        txtFloodCoverAmount.Text = "N/A";
//                    }
//                }
//                txtGrossPremium.Text = _totalVMI.ToString("#000.00");

//                float _totalCMI = 0.0f;
//                if (_dtSeletedItem.Rows[0]["IsCTPL"] != DBNull.Value)
//                {
//                    if (_dtSeletedItem.Rows[0]["IsCTPL"].ToString().ToLower() == "true")
//                    {
//                        _totalCMI = Convert.ToSingle(_dtSeletedItem.Rows[0]["TotalCMI"].ToString());
//                        chkCTPL.Checked = true;
//                    }
//                    else
//                    {
//                        chkCTPL.Checked = false;
//                    }
//                }

//                txtCTPL.Text = _totalCMI.ToString("#,000.00");
//                txtGrossPremium_TextChanged(null, null);
//            }
//        }
//    }

    #endregion

    private void ShowQuoteStatusAlert()
    {
        if (lblCommenceDateStatus.Text == "0" || lblQuoteDateTimeStatus.Text == "0")
        {
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + lblQuoteStatusMessage.Text + "');", true);
        }
    }

    protected void btnBuyNowRefresh_Click(object sender, EventArgs e)
    {
        Session[General.CallPageStartDateTime] = lblStartDateTime.Text;
        lblResetUrl.Text = lblResetUrl.Text.Replace("&buynowrefresh=true", "");
        Response.Redirect(lblResetUrl.Text + "&buynowrefresh=true");
    }

    private bool SendOrderConfirmation()
    {
        bool _retVal = false;

        Int16 IsThai = 1;
        if (chkIsEN.Checked)
        {
            IsThai = 0;
        }

        if (IsThai == 1)
        {
            Session["Language"] = "th-TH";
        }
        else
        {
            Session["Language"] = "en-US";
        }

        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();

        CE.Database.MyDatabase _db = new CE.Database.MyDatabase();

        string _ccemail = string.Empty;



        if (Session[General.UserRole].ToString() == "100")
        {
            _ccemail += Session[General.SMTPReplyTo].ToString();
        }

        string _bccemail = string.Empty;



        System.Data.DataTable _dtSeletectItem = new System.Data.DataTable("SelectedResultItem");
        _dtSeletectItem = _db.GetDataTable("select b.CompanyName, p.* from tblCXBrokerPremium p INNER JOIN tblCXBrokerProvider b "
                                           + " ON p.CXBrokerProviderId = b.CXBrokerProviderId WHERE p.CECarId = " + txtCarId.Text + " And p.CustomerId = " + txtCustomerId.Text + " And p.SelectedStatus = 1");

        if (_dtSeletectItem != null && _dtSeletectItem.Rows.Count > 0)
        {
            string _InsuranceType = "";
            switch (_dtSeletectItem.Rows[0]["ProviderCoverTypeID"].ToString())
            {
                case "10":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassOne;
                    break;
                case "11":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassOneLowCost;
                    break;
                case "20":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassTwo;
                    break;
                case "21":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassTwoPlus;
                    break;
                case "31":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassThreePlus;
                    break;
                case "30":
                    _InsuranceType = Resources.CarInsurance.Insurance_ClassThree;
                    break;
            }

            if (Session["Language"] == "th-TH" && _dtSeletectItem.Rows[0]["BInfo1"].ToString().ToLower() == "true")
            {
                _InsuranceType += " (ตามไมล์)";
            }

            string _strCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("CXCRMIsCXLive");
            string _strVirtualDir = CE.Configuration.MyConfigurationManager.GetAppSettingValue("VirtualDir");

            string _emailTo = txtConfirmEmail.Text;
            string _customername = lblName.Text + " " + lblLastName.Text;
            string _emailSubject = Resources.EmailMessage.Subject; // "Your Car Insurance Quotes on CompareXpress(Thailand)";
            string _mailBody = "";

            Uri myUri = new Uri(HttpContext.Current.Request.Url.ToString());
            string _currentDomainUrl = "http://www.gluaygluay.com/crm"; //"http://" + HttpContext.Current.Request.Url.Host.ToString();
            //if (_strCXLive == "2")
            //{
            //    _currentDomainUrl = "http://" + myUri.Authority;
            //}
            //else
            //{
            //    _currentDomainUrl = "http://" + myUri.Host;
            //}
            //_currentDomainUrl = _currentDomainUrl + "/" + _strVirtualDir;

            //string imgLogoUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("LogoPath");

            _mailBody = "<html>";
            _mailBody += "<head>";
            _mailBody += "<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />";
            _mailBody += "<title>GluayGluay</title>";
            _mailBody += "<style>";
            _mailBody += ".body {";
            _mailBody += "margin-left: 0px;";
            _mailBody += "margin-top: 0px;";
            _mailBody += "margin-right: 0px;";
            _mailBody += "margin-bottom: 0px;";
            _mailBody += "font-family: Arial, sans-serif;";
            _mailBody += "font-size: 14px;";
            _mailBody += "color: #000000;";
            _mailBody += "background-repeat: repeat-x;";
            _mailBody += "background-color: #fff;";
            _mailBody += "text-decoration: none;}";
            _mailBody += "</style>";
            _mailBody += "</head>";
            _mailBody += "<body class='body'>";


            //_mailBody += "<table cellpadding='0' cellspacing='0' border='0' width='800'>";
            //_mailBody += "<tr><td width='570'><table cellspacing='0' cellpadding='0' width='100%' border='0'>";
            //_mailBody += "<tr><td width='50%' valign='top'><strong>" + Resources.Proposal.OrderConfirmation + "</strong><br /><br />";
            //_mailBody += Resources.Proposal.ThankYou; // + "<br/><br/>"
            ////_mailBody += "<br/><strong>" + Resources.Proposal.OrderNo + " </strong>" + _dtSeletectItem.Rows[0]["Info1"].ToString(); //<td width='50%' align='right' valign='top'><img src='" + imgLogoUrl + "' width='130' height='99'/></td>
            //_mailBody += "</td></tr></table>";

            string _garageType = Resources.CarInsurance.Garage_Authorized;
            if (_dtSeletectItem.Rows[0]["Workshop"].ToString() == "1")
            {
                _garageType = Resources.CarInsurance.Garage_Authorized;
            }
            else if (_dtSeletectItem.Rows[0]["Workshop"].ToString() == "2")
            {
                _garageType = Resources.CarInsurance.Garage_Dealer;
            }

            _mailBody += "<table width='630' border='0' cellspacing='0' align='center' cellpadding='0'>";
            _mailBody += "<tr><td valign='top'><span class='email-banner'><img src='http://www.gluaygluay.com/images/email-header.jpg' width='630' height='100' alt='' /></span></td></tr>";
            _mailBody += "<tr><td valign='top'><strong>" + Resources.Proposal.OrderConfirmation + "</strong><br />";
            _mailBody += Resources.Proposal.ThankYou + "<br/><br/></td></tr>";
            _mailBody += "<tr>";
            _mailBody += "<td height='146' valign='top' bgcolor='#C1C1C1'>";
            _mailBody += "<br />";
            _mailBody += "<table width='630' border='0' cellspacing='1' cellpadding='1'>";
            _mailBody += "<tr>";
            _mailBody += "<td height='26' colspan='4' bgcolor='#E7E7E7'>";
            _mailBody += "<span style='font-size: 14px; font-weight: bold; padding-left: 5px; padding-bottom: 5px;";
            _mailBody += "padding-top: 5px;'>" + Resources.Proposal.OrderNo + " " + _dtSeletectItem.Rows[0]["Info1"].ToString() + "</span>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            _mailBody += "<tr>";
            _mailBody += "<td width='130' height='25' bgcolor='#FFFFFF'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 5px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.CarInsurance.FullName + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td width='250' height='25' bgcolor='#FFFFFF'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 5px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += _customername + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td width='120' bgcolor='#FFFFFF'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 5px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.Proposal.OrderDate + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td width='130' bgcolor='#FFFFFF'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 5px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += dateTimeNow.ToString("dd/MMM/yyyy") + "</span>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            _mailBody += "<tr>";
            _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 5px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.Proposal.InsuranceType + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 5px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += _InsuranceType + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td bgcolor='#E7E7E7'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 5px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.Proposal.RefNo + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td bgcolor='#E7E7E7'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 5px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += _dtSeletectItem.Rows[0]["Info2"].ToString() + "</span>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            _mailBody += "<tr>";
            _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 5px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.Proposal.MakeModel + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td height='30' colspan='3' bgcolor='#FFFFFF'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 5px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += lblCarMakeModel.Text + "</span>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            _mailBody += "<tr>";
            _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 5px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.Proposal.CarYear + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td bgcolor='#E7E7E7'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 5px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += lblRegYear.Text + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td bgcolor='#E7E7E7'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 5px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.Proposal.LicensePlateNo + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td bgcolor='#E7E7E7'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 5px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += txtEditLicensePlate.Text + "</span>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            _mailBody += "<tr>";
            _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 5px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.Proposal.GarageType + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 5px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += _garageType + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 5px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.Proposal.NamedDrivers + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 5px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += ddlEditNamedDriver.Text + "</span>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            _mailBody += "<tr>";
            _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 5px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += Resources.Proposal.PolicyStartDate + "</span>";
            _mailBody += "</td>";
            _mailBody += "<td bgcolor='#E7E7E7' colspan='3'>";
            _mailBody += "<span style='font-size: 14px; padding-left: 5px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += lblEditCoverCommencementDate.Text + "</span>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            _mailBody += "</table>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            _mailBody += "</table>";
            _mailBody += "<br />";
            _mailBody += "<br />";

            //_mailBody += "<table cellspacing='0' cellpadding='2' width='800' border='0'>";
            //_mailBody += "<tr><td colspan='2' valign='top'><strong>" + Resources.Proposal.OrderNo + " </strong>" + _dtSeletectItem.Rows[0]["Info1"].ToString() + "</td></tr>";
            //_mailBody += "<tr><td width='50%' valign='top'>" + Resources.Proposal.InsuranceType + " " + _InsuranceType + "</td><td width='50%;' valign='top'>&nbsp;</td>";
            //_mailBody += "</tr><tr><td valign='top'>" + Resources.Proposal.RefNo + ": " + _dtSeletectItem.Rows[0]["Info2"].ToString() + "</td><td valign='top'>" + Resources.Proposal.OrderDate + ": " + dateTimeNow.ToString("dd/MMM/yyyy") + "</td></tr>";
            //_mailBody += "<tr><td valign='top'>" + Resources.CarInsurance.FullName + ": " + _customername + "</td><td valign='top'>" + Resources.Proposal.LicensePlateNo + ": " + txtEditLicensePlate.Text + "</td></tr>";
            //_mailBody += "<tr><td valign='top'>" + Resources.Proposal.MakeModel + ": " + lblCarMakeModel.Text + "</td><td valign='top'>" + Resources.Proposal.CarYear + ": " + lblRegYear.Text + "</td></tr>";
            //_mailBody += "<tr><td valign='top'>" + Resources.Proposal.GarageType + ": " + _garageType + "</td><td valign='top'>" + Resources.Proposal.NamedDrivers + ": " + ddlEditNamedDriver.Text + "</td></tr>";
            //_mailBody += "<tr><td valign='top'>" + Resources.Proposal.PolicyStartDate + ": " + lblEditCoverCommencementDate.Text + " </td><td valign='top'></td></tr>";
            //_mailBody += "</table> <br /><br />";

            _mailBody += "<table width='630' border='0' cellspacing='0' cellpadding='0' align='center'>";
            _mailBody += "<tr>";
            _mailBody += "<td height='129' valign='top' bgcolor='#C1C1C1'>";
            _mailBody += "<table width='630' border='0' cellspacing='1' cellpadding='1'>";


            string _providercompanyid = _dtSeletectItem.Rows[0]["CXBrokerProviderID"].ToString();
            //logo
            string logourl = CE.Global.General.GetProviderCompanyLogo(_providercompanyid);
            if (_dtSeletectItem.Rows[0]["Info1"].ToString().Trim().Length > 4 && _dtSeletectItem.Rows[0]["Info1"].ToString().Trim().Substring(0, 2) == "GG")
            {
                logourl = "/images/providercompanylogo/gluaygluay.png";
            }
            _mailBody += "<tr>";
            _mailBody += "<td align='left' colspan='2' style='background:#FFFFFF;'><img src='" + _currentDomainUrl + logourl + "' width='130' style='padding:3px;'/></td>";
            _mailBody += "</tr>";

            string insurername = _dtSeletectItem.Rows[0]["CompanyName"].ToString();
            if (_dtSeletectItem.Rows[0]["Info1"].ToString().Trim().Length > 4 && _dtSeletectItem.Rows[0]["Info1"].ToString().Trim().Substring(0, 2) == "GG")
            {
                insurername = "GluayGluay.com";
            }
            //insurer name
            _mailBody += "<tr>";
            _mailBody += "<td bgcolor='#E7E7E7'><strong>" + Resources.CarInsuranceResultPage.Insurer + "</strong></td>";
            _mailBody += "<td align='center' bgcolor='#E7E7E7' style='font-weight:bold; color:black;'><strong>" + insurername + "</strong></td>";
            _mailBody += "</tr>";


            //Deductible  
            _mailBody += "<tr>";
            _mailBody += "<td style='background:#FFFFFF;'><strong>" + Resources.CarInsuranceResultPage.DEC + "</strong></td>";
            float _fDEC = 0.0f;
            string _strDEC = _dtSeletectItem.Rows[0]["DEC"].ToString();
            string deductible = "";
            if (float.TryParse(_strDEC, out _fDEC) && _fDEC > 0)
            {
                deductible = String.Format("{0:0,0.00}", _fDEC);
            }
            else
            {
                deductible = Resources.CarInsuranceResultPage.Waived;  //"<img src='" + _currentDomainUrl + "/images/icon/X.png' width='16' alt='NA' />";
            }
            _mailBody += "<td style='background:#FFFFFF;' >" + deductible + "</td>";
            _mailBody += "</tr>";


            string suminsured = _dtSeletectItem.Rows[0]["OwnDamage"].ToString();

            if (suminsured == "0")
            {
                suminsured = "<img src='" + _currentDomainUrl + "/images/icons/X.png' width='16' alt='NA' />";
            }
            else
            {
                float _sumInsured = 0.0f;
                if (float.TryParse(suminsured, out _sumInsured))
                {
                    suminsured = String.Format("{0:0,0}", _sumInsured);
                }
            }
            //Own Damage
            _mailBody += "<tr>";
            _mailBody += "<td style='background:#E7E7E7'><strong>" + Resources.CarInsuranceResultPage.OwnDamage + "</strong></td>";
            _mailBody += "<td style='background:#E7E7E7' >" + suminsured + "</td>";
            _mailBody += "</tr>";

            //Fire
            string firetheft = _dtSeletectItem.Rows[0]["FireTheft"].ToString();
            if (firetheft == "0")
            {
                firetheft = "<img src='" + _currentDomainUrl + "/images/icons/X.png' width='16' alt='NA' />";
            }
            _mailBody += "<tr>";
            _mailBody += "<td style='background:#FFFFFF'><strong>" + Resources.CarInsuranceResultPage.FireTheft + "</strong></td>";
            _mailBody += "<td style='background:#FFFFFF'>" + firetheft + "</td>";
            _mailBody += "</tr>";



            //TPPD
            _mailBody += "<tr>";
            _mailBody += "<td style='background:#E7E7E7'><strong>" + Resources.CarInsuranceResultPage.TPPD + "</strong></td>";
            _mailBody += "<td style='background:#E7E7E7'>" + _dtSeletectItem.Rows[0]["TPPD"].ToString() + "</td>";
            _mailBody += "</tr>";

            //TPBIA
            _mailBody += "<tr>";
            _mailBody += "<td style='background:#FFFFFF'><strong>" + Resources.CarInsuranceResultPage.TPBIA + "</strong></td>";
            _mailBody += "<td style='background:#FFFFFF'>" + _dtSeletectItem.Rows[0]["TPBIA"].ToString() + "</td>";
            _mailBody += "</tr>";

            //TPBIP
            _mailBody += "<tr>";
            _mailBody += "<td style='background:#E7E7E7'><strong>" + Resources.CarInsuranceResultPage.TPBIP + "</strong></td>";
            _mailBody += "<td style='background:#E7E7E7'>" + _dtSeletectItem.Rows[0]["TPBIP"].ToString() + "</td>";
            _mailBody += "</tr>";

            //PA Driver
            _mailBody += "<tr>";
            _mailBody += "<td style='background:#FFFFFF'><strong>" + Resources.CarInsuranceResultPage.PADriver + "</strong></td>";
            _mailBody += "<td style='background:#FFFFFF'>" + _dtSeletectItem.Rows[0]["PADriver"].ToString() + "</td>";
            _mailBody += "</tr>";


            string _MedicalExpense = _dtSeletectItem.Rows[0]["MedicalExpense"].ToString();
            string medicalExpense = "";

            if (_MedicalExpense == string.Empty || _MedicalExpense == "0")
            {
                medicalExpense = "<img src='" + _currentDomainUrl + "/images/icons/X.png' width='16' alt='NA' />";
            }
            else
            {
                medicalExpense = _MedicalExpense;
            }

            //Medical Expense
            _mailBody += "<tr>";
            _mailBody += "<td style='background:#E7E7E7'><strong>" + Resources.CarInsuranceResultPage.MED + "</strong></td>";
            _mailBody += "<td style='background:#E7E7E7'>" + medicalExpense + "</td>";
            _mailBody += "</tr>";

            //BB
            _mailBody += "<tr>";
            _mailBody += "<td style='background:#FFFFFF'><strong>" + Resources.CarInsuranceResultPage.BailBond + "</strong></td>";
            _mailBody += "<td style='background:#FFFFFF'>" + String.Format("{0:#,0}", Convert.ToSingle(_dtSeletectItem.Rows[0]["BailBond"].ToString())) + "</td>";
            _mailBody += "</tr>";

            string bgColor = "FFFFFF";

            //Flood Cover
            if (_dtSeletectItem.Rows[0]["Info5"] != DBNull.Value)
            {
                float _floodCover = 0.0f;

                _mailBody += "<tr>";
                _mailBody += "<td style='background:#E7E7E7'><strong>" + Resources.CarInsuranceResultPage.FloodCover + "</strong></td>";
                if (float.TryParse(_dtSeletectItem.Rows[0]["Info5"].ToString(), out _floodCover))
                {
                    _mailBody += "<td style='background:#E7E7E7'>" + String.Format("{0:#,0}", _floodCover) + "</td>";
                }
                else
                {
                    _mailBody += "<td style='background:#E7E7E7'>" + _dtSeletectItem.Rows[0]["Info5"].ToString() + "</td>";
                }
                _mailBody += "</tr>";

                bgColor = "E7E7E7";
            }

            string _TotalVMI = _dtSeletectItem.Rows[0]["TotalVMI"].ToString();
            string _TotalCMI = _dtSeletectItem.Rows[0]["TotalCMI"].ToString();
            string _FinalAnnualPremium = _dtSeletectItem.Rows[0]["FinalAnnualPremium"].ToString();
            string _FinalAnnualPremiumNoDisc = string.Empty;


            //Sakthi Change on 04 Dec 2012 -- Start
            Int64 _strBrokerProvider = 0;
            string _strPaymentOption = "FP";
            string _strMonthlyInstallment = "0.00";
            Int32 _Installments = 3;
            Int32 _Install = _Installments - 1;
            string _strFirstInstallmentDesc = "";
            string _strLastInstallmentDesc = "";
            string _InerestFree = "<img src='" + _currentDomainUrl + "/images/icons/tick.gif' width='16' alt='NA' />";
            string _BankCode = "BKK";

            if (_dtSeletectItem.Rows[0]["CXBrokerProviderId"] != DBNull.Value && _dtSeletectItem.Rows[0]["CXBrokerProviderId"].ToString() != string.Empty)
            {
                _strBrokerProvider = Convert.ToInt32(_dtSeletectItem.Rows[0]["CXBrokerProviderId"].ToString());
            }

            if (_dtSeletectItem.Rows[0]["PaymentOption"] != DBNull.Value && _dtSeletectItem.Rows[0]["PaymentOption"].ToString() != string.Empty)
            {
                _strPaymentOption = _dtSeletectItem.Rows[0]["PaymentOption"].ToString();
            }

            if (_dtSeletectItem.Rows[0]["NoofInstallMent"] != DBNull.Value && _dtSeletectItem.Rows[0]["NoofInstallMent"].ToString() != string.Empty)
            {
                _Installments = Convert.ToInt32(_dtSeletectItem.Rows[0]["NoofInstallMent"].ToString());
            }

            if (_dtSeletectItem.Rows[0]["Bank"] != DBNull.Value && _dtSeletectItem.Rows[0]["Bank"].ToString() != string.Empty)
            {
                _BankCode = _dtSeletectItem.Rows[0]["Bank"].ToString();
            }
            _strFirstInstallmentDesc = "(1 " + Resources.CarInsurance.To + " " + _Install.ToString() + " " + Resources.CarInsurance.Months + ")";
            _strLastInstallmentDesc = Resources.CarInsurance.LastMonthInstallment;

            //Yui@31/07/2014 Remove LMG
            //if (_strBrokerProvider == 29)
            //{
            //    _strMonthlyInstallment = (Convert.ToSingle(_dtSeletectItem.Rows[0]["InstallmentAmountWD"].ToString())).ToString("#,000.00");
            //    if (_BankCode == "CHINS")
            //    {
            //        _InerestFree = "<img src='" + _currentDomainUrl + "/images/icons/tick.gif' width='16' alt='NA' />";
            //        if (_Installments == 2)
            //        {
            //            _strMonthlyInstallment = "50:50";
            //        }
            //        else if (_Installments == 3)
            //        {
            //            _strMonthlyInstallment = "40:30:30";
            //        }
            //        else if (_Installments == 4)
            //        {
            //            _strMonthlyInstallment = "25:25:25:25";
            //        }
            //    }
            //    else if (_BankCode == "KBANK")
            //    {
            //        _InerestFree = "<img src='" + _currentDomainUrl + "/images/icons/tick.gif' width='16' alt='NA' />";
            //    }
            //    else
            //    {
            //        _InerestFree = "<img src='" + _currentDomainUrl + "/images/icons/X.png' width='16' alt='NA' />";
            //    }
            //}
            //else
            //{
                _strMonthlyInstallment = (Convert.ToSingle(_dtSeletectItem.Rows[0]["InstallmentAmountWOD"].ToString())).ToString("#,000.00");
            //}
            //Sakthi Change on 04 Dec 2012 -- End

            bgColor = BGColor(bgColor);

            if (_dtSeletectItem.Rows[0]["FInfo1"] != DBNull.Value)
            {
                _FinalAnnualPremiumNoDisc = _dtSeletectItem.Rows[0]["FInfo1"].ToString();

                //Annual Premium (tax + duty)
                _mailBody += "<tr>";
                _mailBody += "<td style='background:#" + bgColor + "'><strong>" + Resources.CarInsuranceResultPage.AnnualPremium + "</strong></td>";
                _mailBody += "<td style='background:#" + bgColor + "'>";

                _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(_TotalVMI)) + "</strong>";
                _mailBody += "</td>";
                _mailBody += "</tr>";

                bgColor = BGColor(bgColor);

                //CTPL
                if (_dtSeletectItem.Rows[0]["IsIncludeCMI"].ToString() == "True")
                {
                    //CMI
                    _mailBody += "<tr>";
                    _mailBody += "<td style='background:#" + bgColor + "'><strong>" + Resources.CarInsuranceResultPage.CTPL + "</strong></td>";
                    _mailBody += "<td style='background:#" + bgColor + "'>";

                    _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(_TotalCMI)) + "</strong>";
                    _mailBody += "</td>";
                    _mailBody += "</tr>";

                    bgColor = BGColor(bgColor);

                    //Total
                    _mailBody += "<tr>";
                    _mailBody += "<td style='background:#" + bgColor + "'><strong>" + Resources.CarInsuranceResultPage.Total + "</strong></td>";
                    _mailBody += "<td style='background:#" + bgColor + "'>";
                    _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(_FinalAnnualPremiumNoDisc)) + "</strong>";
                }

                bgColor = BGColor(bgColor);
                _mailBody += "<tr>";
                if (_strPaymentOption == "IP")
                {
                    _mailBody += "<td style='background:#" + bgColor + "'><strong>" + Resources.CarInsuranceResultPage.SpecialPrice + "</strong> (" + Resources.CarInsuranceResultPage.Valid7Days + ")</td>";
                }
                else
                {
                    _mailBody += "<td style='background:#" + bgColor + "'><strong>" + Resources.CarInsuranceResultPage.SpecialPrice + "</strong> (" + Resources.CarInsuranceResultPage.Valid7Days + ")</td>";
                }
                _mailBody += "<td style='background:#" + bgColor + "'>";
                _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(_FinalAnnualPremium)) + "</strong> ";

            }
            else
            {
                //FOR OLD QUOTATION - Temp
                #region BEFORE 28/Sep/2012
                //CTPL
                if (_dtSeletectItem.Rows[0]["IsIncludeCMI"].ToString() == "True")
                {
                    //premium before ctpl
                    _mailBody += "<tr>";
                    _mailBody += "<td style='background:#" + bgColor + "'><strong>" + Resources.General.AnnualPremium + "</strong></td>";
                    _mailBody += "<td style='background:#" + bgColor + "'>";

                    float _newAnnualPremium = Convert.ToSingle(_FinalAnnualPremium) - Convert.ToSingle(_TotalCMI);

                    _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(_newAnnualPremium)) + "</strong>";
                    _mailBody += "</td>";
                    _mailBody += "</tr>";

                    bgColor = BGColor(bgColor);

                    //ctplamount
                    _mailBody += "<tr>";
                    _mailBody += "<td style='background:#" + bgColor + "'><strong>" + Resources.CarInsuranceResultPage.CTPL + "</strong></td>";
                    _mailBody += "<td style='background:#" + bgColor + "'>";

                    _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(_TotalCMI)) + "</strong>";
                    _mailBody += "</td>";
                    _mailBody += "</tr>";

                }

                bgColor = BGColor(bgColor);

                //premium
                _mailBody += "<tr>";
                _mailBody += "<td style='background:#" + bgColor + "'><strong>" + Resources.CarInsuranceResultPage.TotalVMI + "</strong></td>";
                _mailBody += "<td style='background:#" + bgColor + "'>";

                if (_dtSeletectItem.Rows[0]["IsIncludeCMI"].ToString() == "False")
                {
                    _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(_FinalAnnualPremium)) + "</strong>";
                }
                else
                {
                    _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(_FinalAnnualPremium)) + "</strong>";
                }
                #endregion
            }

            
            //Sakthi Change on 04 Dec 2012 -- Start
            if (_strPaymentOption == "IP")
            {
                bgColor = BGColor(bgColor);
                if (_BankCode != "CHINS")
                {
                    _mailBody += "<tr>";
                    _mailBody += "<td style='background:#" + bgColor + "'><strong>" + Resources.CarInsurance.MonthlyInstallments + "</strong></td>";
                    _mailBody += "<td style='background:#" + bgColor + "'>";
                    _mailBody += "<br/><strong>" + String.Format("{0:0,0.00}", Convert.ToSingle(_strMonthlyInstallment)) + "</strong> ";
                }
                else
                {
                    _mailBody += "<tr>";
                    _mailBody += "<td style='background:#" + bgColor + "'><strong>" + Resources.CarInsurance.MonthlyInstallments + "</strong></td>";
                    _mailBody += "<td style='background:#" + bgColor + "'>";
                    _mailBody += "<br/><strong>" + _strMonthlyInstallment + "</strong> ";

                }

                bgColor = BGColor(bgColor);

                _mailBody += "<tr>";
                _mailBody += "<td style='background:#" + bgColor + "'><strong>" + Resources.CarInsurance.InstallmentperMonth + "</strong></td>";
                _mailBody += "<td style='background:#" + bgColor + "'>";
                _mailBody += "<br/><strong>" + _Installments.ToString() + " " + Resources.CarInsurance.Months + "</strong> ";

                bgColor = BGColor(bgColor);

                _mailBody += "<tr>";
                _mailBody += "<td style='background:#" + bgColor + "'><strong>" + Resources.CarInsurance.CreditCardby + "</strong></td>";
                _mailBody += "<td style='background:#" + bgColor + "'>";
                _mailBody += "<br/><strong>" + GetBankName(_BankCode) + "</strong> ";

                bgColor = BGColor(bgColor);

                _mailBody += "<tr>";
                _mailBody += "<td style='background:#" + bgColor + "'><strong>" + Resources.CarInsurance.ZeroPercentInterestFree + "</strong></td>";
                _mailBody += "<td style='background:#" + bgColor + "'>";
                _mailBody += "<br/><strong>" + _InerestFree + "</strong> ";
            }


            //Sakthi Change on 04 Dec 2012 -- End

            _mailBody += "</td>";
            _mailBody += "</tr>";
            _mailBody += "</table>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            _mailBody += "</table>";
            _mailBody += "<br/><br/>";

            _mailBody += "<table style='line-height: 20px;' width='630' border='0' cellspacing='0' cellpadding='0' align='center'>";
            _mailBody += "<tr>";
            _mailBody += "<td width='620' height='26' colspan='4' bgcolor='#FFFFFF'>";


            _mailBody += "<u>" + Resources.Proposal.ForBankIn + "</u>";
            _mailBody += "<br/>" + Resources.Proposal.ForBankInMsg1;


            _mailBody += "<br/>";
            _mailBody += "<br/>" + Resources.Proposal.ForBankInMsg2;
            _mailBody += "<br/>";

            _mailBody += "<br/><strong>" + Resources.Proposal.Remarks + "</strong>";
            _mailBody += "<br/>" + Resources.Proposal.RemarksMsg1;
            _mailBody += "<br/>";

            _mailBody += "<hr />";
            _mailBody += "<br/>";
            _mailBody += Resources.EmailMessage.Footer;
            _mailBody += "<br/>";
            _mailBody += "<hr />";

            _mailBody += "<br/><strong>" + Resources.Proposal.CompareXpress + "</strong>";
            _mailBody += "<br/>" + Resources.Proposal.CompareXpressAddress;

            _mailBody += "</td></tr>";
            _mailBody += "<tr><td id='email_footer'>";
            _mailBody += "</td></tr></table>";

            _mailBody += "<br />";

            _mailBody += "<table width='300' border='0' align='center' cellpadding='0' cellspacing='0'>";
            _mailBody += "<tr>";
            _mailBody += "<td width='44' style='text-align: center'>";
            _mailBody += "<a href='https://www.facebook.com/GGmotor' target='_blank'><img src='http://www.gluaygluay.com/images/icons/fb-big.png' width='44' height='42'></a>";
            _mailBody += "</td>";
            _mailBody += "<td width='44' style='text-align: center'>";
            _mailBody += "<a href='https://plus.google.com/+Gluaygluay/posts' target='_blank'><img src='http://www.gluaygluay.com/images/icons/g-plus-big.png' width='44' height='42'></a>";
            _mailBody += "</td>";
            _mailBody += "<td width='44' style='text-align: center'>";
            _mailBody += "<a href='http://www.youtube.com/channel/UCZ4gMtlXymBHxvcXO2cR1vA' target='_blank'><img src='http://www.gluaygluay.com/images/icons/youtube-big.png' width='44' height='42'></a>";
            _mailBody += "</td>";
            _mailBody += "<td width='44' style='text-align: center'>";
            _mailBody += "<a href='http://iconosquare.com/ggmotor' target='_blank'><img src='http://www.gluaygluay.com/images/icons/instagram-big.png' width='44' height='42'></a>";
            _mailBody += "</td>";
            _mailBody += "<td width='43' style='text-align: center'>";
            _mailBody += "<a href='http://www.linkedin.com/company/-com-gluaygluay-com-' target='_blank'><img src='http://www.gluaygluay.com/images/icons/linkedin-big.png' width='44' height='42'></a>";
            _mailBody += "</td>";
            _mailBody += "</tr>";
            _mailBody += "</table>";

            _mailBody += "<hr />";
            _mailBody += "<br/>";

            _mailBody += "<table width='300' border='0' align='center' cellpadding='0' cellspacing='0'>";
            _mailBody += "<tr>";
            _mailBody += "<td style='text-align: center'>";

            string YearEn = dateTimeNow.Year.ToString();
            _mailBody += "© " + YearEn + " gluaygluay.com. All rights reserved.";
            _mailBody += "<br />" + Resources.EmailMessage.NoReply;
            _mailBody += "</td>";
            _mailBody += "</tr>";
            _mailBody += "</table>";
            
            _mailBody += "</body>";
            _mailBody += "</html>";


            //[Yui] @03/09/2013 Add Cash Installment form(pdf) -- Start --
            string _fileNameCashInstallment = string.Empty;
            if (_strPaymentOption == "IP")
            {
                if (_BankCode == "CHINS")
                {
                    string CarPlate = txtEditLicensePlate.Text;
                    string ContractNo = _dtSeletectItem.Rows[0]["Info1"].ToString();
                    bool IsIncludeCMI = (bool)_dtSeletectItem.Rows[0]["IsIncludeCMI"];
                    string Premium1 = "";
                    float _premium1 = 0.0f;
                    if (float.TryParse(_dtSeletectItem.Rows[0]["Premium"].ToString(), out _premium1))
                    {
                        Premium1 = _premium1.ToString("#0.00"); //เบี้ยประกันภัยสุทธิ
                    }

                    string Premium2 = "";
                    float _premium2 = 0.0f;
                    if (float.TryParse(_dtSeletectItem.Rows[0]["TotalVMI"].ToString(), out _premium2))
                    {
                        Premium2 = _premium2.ToString("#0.00"); //เบี้ยประกันภัยรวมภาษีอากรณ์ : เบี้ยประกันภัยรวมไม่หักส่วนลด
                    }

                    string Premium3 = "";
                    float _premium3 = 0.0f;
                    if (float.TryParse(_dtSeletectItem.Rows[0]["FinalAnnualPremium"].ToString(), out _premium3))
                    {
                        Premium3 = _premium3.ToString("#0.00"); //เบี้ยประกันภัยที่ขอสินเชื่อ
                    }

                    string NoOfInstall = _Installments.ToString();
                    DateTime modDate = (DateTime)_dtSeletectItem.Rows[0]["ModifiedDate"];
                    string Install1 = "";
                    string InstallDate1 = "";
                    float _install1 = 0.0f;
                    if (float.TryParse(_dtSeletectItem.Rows[0]["InstallmentAmountWOD"].ToString(), out _install1))
                    {
                        Install1 = _install1.ToString("#0.00");
                        InstallDate1 = modDate.ToString("dd/MM/yyyy", new System.Globalization.CultureInfo("th-TH"));
                    }
                    string Install2 = "";
                    string InstallDate2 = "";
                    if (_Installments >= 2)
                    {
                        float _install2 = 0.0f;
                        if (float.TryParse(_dtSeletectItem.Rows[0]["LastInstallmentAmountWOD"].ToString(), out _install2))
                        {
                            Install2 = _install2.ToString("#0.00");
                            InstallDate2 = modDate.AddMonths(1).ToString("dd/MM/yyyy", new System.Globalization.CultureInfo("th-TH"));
                        }
                    }
                    string Install3 = "";
                    string InstallDate3 = "";
                    if (_Installments >= 3)
                    {
                        float _install3 = 0.0f;
                        if (float.TryParse(_dtSeletectItem.Rows[0]["LastInstallmentAmountWOD"].ToString(), out _install3))
                        {
                            Install3 = _install3.ToString("#0.00");
                            InstallDate3 = modDate.AddMonths(2).ToString("dd/MM/yyyy", new System.Globalization.CultureInfo("th-TH"));
                        }
                    }
                    string Install4 = "";
                    string InstallDate4 = "";
                    if (_Installments >= 4)
                    {
                        float _install4 = 0.0f;
                        if (float.TryParse(_dtSeletectItem.Rows[0]["LastInstallmentAmountWOD"].ToString(), out _install4))
                        {
                            Install4 = _install4.ToString("#0.00");
                            InstallDate4 = modDate.AddMonths(3).ToString("dd/MM/yyyy", new System.Globalization.CultureInfo("th-TH"));
                        }
                    }
                    CashInstallmentPDFOutput _cashInstallmentPdf = CreateCashInstallmentPDFObject(CarPlate, ContractNo, Premium1,
                             Premium2, Premium3, NoOfInstall, Install1, Install2, Install3, Install4,
                             InstallDate1, InstallDate2, InstallDate3, InstallDate4, IsIncludeCMI);
                    _fileNameCashInstallment = _cashInstallmentPdf.GeneratePDF();
                }
            }

            bool _mailStatus = false;

            string[] _fileList = new string[2];
            if (_fileNameCashInstallment != string.Empty)
            {
                _fileList = new string[3];
            }
            _fileList[0] = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NonGGCCFilePath");
            _fileList[1] = CE.Configuration.MyConfigurationManager.GetAppSettingValue("NonGGKYCFormFilePath");
            if (_fileNameCashInstallment != string.Empty) _fileList[2] = _fileNameCashInstallment;


            if (Session[General.SMTPAccountName].ToString().Contains("gluaygluay.com"))
            {
                _mailStatus = MyMailManager.SendGGMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _emailTo, _ccemail, _bccemail, _emailSubject + " (Ref No : " + _dtSeletectItem.Rows[0]["Info1"].ToString() + ") ", _mailBody, Session[General.SMTPReplyTo].ToString(), _fileList);
            }
            else if (Session[General.SMTPAccountName].ToString().Contains("comparexpress.co.th"))
            {
                _mailStatus = MyMailManager.SendGGMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _emailTo, _ccemail, _bccemail, _emailSubject + " (Ref No : " + _dtSeletectItem.Rows[0]["Info1"].ToString() + ") ", _mailBody, Session[General.SMTPReplyTo].ToString(), _fileList);
            }
            else if (Session[General.SMTPAccountName].ToString().Contains("gmail.com"))
            {
                _mailStatus = MyMailManager.SendGGMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _emailTo, _ccemail, _bccemail, _emailSubject + " (Ref No : " + _dtSeletectItem.Rows[0]["Info1"].ToString() + ") ", _mailBody, Session[General.SMTPReplyTo].ToString(), _fileList);
            }
            else
            {
                _mailStatus = MyMailManager.SendGGMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _emailTo, _ccemail, _bccemail, _emailSubject + " (Ref No : " + _dtSeletectItem.Rows[0]["Info1"].ToString() + ") ", _mailBody, Session[General.SMTPReplyTo].ToString(), _fileList);
            }

            if (_mailStatus)
            {
                _retVal = true;
            }
            else
            {
                _retVal = false;
            }
        }
        else
        {
            lblSendOrderConfirmationMessage.Text = "<br/>" + Resources.General.OrderConfirmationNoSelectedItem;
        }

        if (lblLangOption.Text == "1")
        {
            Session["Language"] = "th-TH";
        }
        else
        {
            Session["Language"] = "en-US";
        }

        CE.Global.General.SetCulture();
        base.InitializeCulture();

        return _retVal;
    }

    private string BGColor(string colorCode)
    {
        if (colorCode == "E7E7E7")
            return "FFFFFF";
        else
            return "E7E7E7"; 
    }

    private string GetBankName(string BankCode)
    {
        string _BankName = "";
        if (BankCode == "CHINS")
        {
            _BankName = Resources.CarInsurance.CashInstallment;
        }
        else if (BankCode == "BKK")
        {
            _BankName = Resources.CarInsurance.BankBKK;
        }
        else if (BankCode == "KBANK")
        {
            _BankName = Resources.CarInsurance.BankK;
        }
        else if (BankCode == "KTC")
        {
            _BankName = Resources.CarInsurance.BankKTC;
        }
        else if (BankCode == "CITI")
        {
            _BankName = Resources.CarInsurance.BankCITI;
        }
        else if (BankCode == "AYA")
        {
            _BankName = Resources.CarInsurance.BankAYA;
        }
        else if (BankCode == "CTRL")
        {
            _BankName = Resources.CarInsurance.CentralCard;
        }
        else if (BankCode == "RBSN")
        {
            _BankName = Resources.CarInsurance.RobinsonCard;
        }
        else if (BankCode == "HPRO")
        {
            _BankName = Resources.CarInsurance.HomeproCard;
        }
        return _BankName;
    }

    protected void btnSendOrderConfirmation_Click(Object sender, EventArgs e)
    {
        lblSendOrderConfirmationMessage.Text = string.Empty;
        if (SendOrderConfirmation())
        {
            BrokerPremiumDB _premiumDB = new BrokerPremiumDB();

            if (_premiumDB.SaveQuotationEmail(Convert.ToInt32(txtCarId.Text),
                            Convert.ToInt64(txtCustomerId.Text),
                            Convert.ToInt64(Session[General.UserId].ToString()),
                            txtEditLicensePlate.Text,
                            txtConfirmEmail.Text, 3, "") > 0)
            {
                lblSendOrderConfirmationMessage.Text += "<br/>" + Resources.General.OrderConfirmationSent + " at " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm tt");
            }
            else
            {
                lblSendOrderConfirmationMessage.Text += "<br/> " + Resources.General.OrderConfirmationSent + " Saving confirm email was failed.";
            }
        }
        else
        {
            lblSendOrderConfirmationMessage.Text += "<br/>" + Resources.General.OrderConfirmationFailed;
        }
    }

    protected void btnNewPremium_Click(object sender, EventArgs e)
    {
        //LoadBrokerProvider();
        ClearFields();
        txtGG.Text = "PROVIDER";
        txtTescoAmount.Text = "0";

        if ((Convert.ToInt32(txtPremiumId.Text) > 0) || (Convert.ToInt32(txtPremiumId.Text) <= 0 && grvPremiumList.Rows.Count < 4))
        {
            lblPremiumError.Text = string.Empty;
            lblPremiumMessage.Text = string.Empty;
        }
        else
        {
            lblPremiumMessage.Text = string.Empty;
            lblPremiumError.Text = "Please create only Max 4 quotations!";
        }
    }

    private void LoadDiscountPercentageList()
    {
        // แก้ไขจากที่เขียนมั่ว

        int _maxPercentage = 0;
        int _providerComId = Convert.ToInt32(ddlBrokerProvider.Text);

        //16 Jul 2012 to 30 Sep 2012 (9%)
        //01 Oct 2012 to 31 Dec 2012 (5%) - After 7 Days, 0%

        DateTime _dtStartDate = new DateTime(2012, 09, 01);
        DateTime _dtEndDate = new DateTime(2099, 12, 31);
        if (DateTime.Compare(dateTimeNow, _dtStartDate) > 0 && DateTime.Compare(dateTimeNow, _dtEndDate) < 0)
        {
            // ใช้อันนี้
            //if (_providerComId == 41 && ddlBrokerCoverType.Text == "11")
            //{
            //    _maxPercentage = 0;
            //}

            // Can has discount for MIR 31Mar2015
            //if (_providerComId == 39) // MIR Changed @ 29 Apr 2013 - Effective from 01 May 2013
            //{
            //    _maxPercentage = 0;
            //}
            //else
            //{
            _maxPercentage = 5;
            if (Session[General.UserCampaign] != null && Session[General.UserCampaign].ToString() == "1001")
            {
                _maxPercentage = 9;
            }

            //if (chkCompanyStaff.Checked)
            //{
            //    _maxPercentage = 15;// 12; Changed on 30 Nov 2012
            //}

            if (_providerComId == 41 || _providerComId == 43) //KURNIA and SMK
            {
                ddlDiscountPercentage.Enabled = true;
            }

            //Sakthi on 02 Oct 2012 -- Start
            Int64 _PremiumId = 0;
            if (!Int64.TryParse(txtPremiumId.Text, out _PremiumId))
            {
                _PremiumId = 0;
            }

            if (_PremiumId > 0)
            {
                if (_discountPercentage > 0)
                {
                    _maxPercentage = _discountPercentage;
                }
                else
                {
                    Int32 percert = _maxPercentage;
                    DataSet _dsPremium = new DataSet();
                    _dsPremium = GetBrokerPremiumbyPremiumId(_PremiumId);
                    if (_dsPremium != null && _dsPremium.Tables.Count > 0 && _dsPremium.Tables[0].Rows.Count > 0)
                    {
                        if (_dsPremium.Tables[0].Rows[0]["DiscountPercentage"] != DBNull.Value)
                        {
                            Int32.TryParse(_dsPremium.Tables[0].Rows[0]["DiscountPercentage"].ToString(), out percert);
                            if (percert > 0)
                            {
                                _maxPercentage = percert;
                            }
                        }
                    }
                }
            }
            //Sakthi on 02 Oct 2012 -- End

            if (lblRenewalStaus.Text == "1" || lblRenewalStaus.Text == "2")
            {
                if (_maxPercentage < 7)
                    _maxPercentage = 7; //8;  Updated on 06 May 2013
            }

            if (txtGG.Text.Trim() == "GGSPECIAL")
            {
                _maxPercentage = 18;
            }

            if (chkCompanyStaff.Checked)
            {
                _maxPercentage = 15;// 12; Changed on 25 Jan 2013
            }
            //}
        }
        else
        {
            //ไม่ใช้มั้ง งง?
            #region ???
            //31	Chartis
            //46	Tokio Marine
            //41	Kurnia
            //35	KrungThai
            //33	MuangThai
            //32	BKI
            //29	LMG  Insurance
            //12	MSIG
            //11	Allianz CP
            //16	AXA

            DateTime _dtCoverCommDate = dateTimeNow;
            if (lblCoverCommencementDate.Text != string.Empty)
            {
                _dtCoverCommDate = Convert.ToDateTime(lblCoverCommencementDate.Text);
            }
            DateTime _dtThreeDayPlus = Convert.ToDateTime(dateTimeNow.AddDays(3).ToString("dd/MMM/yyyy"));
            DateTime _dtEditCoverCommDate = Convert.ToDateTime(lblEditCoverCommencementDate.Text);

            //              ≤ 3 days	≥ 4 days
            // 16     AXA	    2%	        7%
            // 11     AZCP	    2%	        7%
            // 32     BKI	    2%	        7%
            // 31     CHARTIS	4%	        13%
            // 41     KURNIA	4%	        13%
            // 29     LMG	    4%	        11%
            // 12     MSIG	    4%	        13%
            // 33     MTI	    2%	        8%
            // 46     TOKIO	    2%	        5%

            if (_providerComId == 41 || divCompletedQuoteDetails.Visible == false)
            {
                if (DateTime.Compare(_dtThreeDayPlus, _dtEditCoverCommDate) > 0)
                {
                    if (_providerComId == 16) //AXA
                    {
                        _maxPercentage = 2;
                    }
                    else if (_providerComId == 11) // AZCP
                    {
                        _maxPercentage = 2;
                    }
                    else if (_providerComId == 32) //BKI
                    {
                        _maxPercentage = 2;
                    }
                    else if (_providerComId == 31) //CHARTIS
                    {
                        _maxPercentage = 4;
                    }
                    else if (_providerComId == 41) //KURNIA
                    {
                        _maxPercentage = 4;
                    }
                    else if (_providerComId == 29) //LMG
                    {
                        _maxPercentage = 4;
                    }
                    else if (_providerComId == 12) //MSIG
                    {
                        _maxPercentage = 4;
                    }
                    else if (_providerComId == 33) //MTI
                    {
                        _maxPercentage = 2;
                    }
                    else if (_providerComId == 35) //KPI
                    {
                        _maxPercentage = 2;
                    }
                    else if (_providerComId == 46) //TOKIO
                    {
                        _maxPercentage = 2;
                    }
                }
                else
                {
                    if (_providerComId == 16) //AXA
                    {
                        _maxPercentage = 7;
                    }
                    else if (_providerComId == 11) // AZCP
                    {
                        _maxPercentage = 7;
                    }
                    else if (_providerComId == 32) //BKI
                    {
                        _maxPercentage = 7;
                    }
                    else if (_providerComId == 31) //CHARTIS
                    {
                        _maxPercentage = 13;
                    }
                    else if (_providerComId == 41) //KURNIA
                    {
                        _maxPercentage = 13;
                    }
                    else if (_providerComId == 29) //LMG
                    {
                        _maxPercentage = 11;
                    }
                    else if (_providerComId == 12) //MSIG
                    {
                        _maxPercentage = 13;
                    }
                    else if (_providerComId == 33) //MTI
                    {
                        _maxPercentage = 8;
                    }
                    else if (_providerComId == 35) //KPI
                    {
                        _maxPercentage = 10;
                    }
                    else if (_providerComId == 46) //TOKIO
                    {
                        _maxPercentage = 5;
                    }
                }
            }
            else
            {
                _maxPercentage = 10;
            }

            #endregion
        }

        ddlDiscountPercentage.Items.Clear();
        if (txtGG.Text.Trim() != "GGSPECIAL")
        {
            for (int i = _maxPercentage; i >= 0; i--)
            {
                ddlDiscountPercentage.Items.Add(new ListItem(i.ToString() + " " + "%", i.ToString()));
            }
        }
        else
        {
            ddlDiscountPercentage.Items.Add(new ListItem(_maxPercentage.ToString() + " " + "%", _maxPercentage.ToString()));
            ddlDiscountPercentage.Items.Add(new ListItem("0 %", "0"));
            ddlDiscountPercentage.Text = _maxPercentage.ToString();
            ddlDiscountPercentage.Enabled = false;
        }

        // มีทำไม งง?
        //if (divCompletedQuoteDetails.Visible)
        //    ddlDiscountPercentage.Text = _maxPercentage.ToString();

        //if (lblRenewalStaus.Text == "1" || lblRenewalStaus.Text == "2")
        //{
        //    ddlDiscountPercentage.Text = "0";
        //}

        if (_providerComId == 41 || _providerComId == 43) //KURNIA and SMK
        {
            ddlDiscountPercentage.Text = "0";
        }
        else
        {
            if (DateTime.Compare(dateTimeNow, _dtStartDate) > 0 && DateTime.Compare(dateTimeNow, _dtEndDate) < 0)
            {
                if (_discountPercentage >= 0)
                {
                    //ddlDiscountPercentage.Text = _discountPercentage.ToString();
                    ddlDiscountPercentage.SelectedIndex = ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue(_discountPercentage.ToString()));
                }
                else
                {
                    //ddlDiscountPercentage.Text = _maxPercentage.ToString();
                    ddlDiscountPercentage.SelectedIndex = ddlDiscountPercentage.Items.IndexOf(ddlDiscountPercentage.Items.FindByValue(_maxPercentage.ToString()));
                }
            }
        }

        ddlDiscountPercentage_SelectedIndexChanged(null, null);
    }

    //Sakthi on 02 Oct 2012 -- Start
    public DataSet GetBrokerPremiumbyPremiumId(Int64 CXBrokerPremiumId)
    {
        MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
        SortedList _sPara = new SortedList();
        string _spName = "sprocCXBrokerPremiumDiscountPercentageSelectSingleItem";
        _sPara.Add("@CXBrokerPremiumId", CXBrokerPremiumId);
        DataSet _ds = new DataSet();
        return _ds = _db.GetDataSet(_spName, _sPara);
    }

    private void LoadMonthlyInstallment()
    {
        ddlCreditCard.Items.Clear();
        ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));

        //ddlPaymentOption.Items.Clear();
        //ddlPaymentOption.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        //ddlPaymentOption.Items.Add(new ListItem(Resources.CarInsurance.Installment, "IP"));
        //ddlPaymentOption.Items.Add(new ListItem(Resources.CarInsurance.AnnualPayment, "FP"));

        if (ddlBrokerProvider.SelectedIndex > 0)
        {
            string IPDiscount = CE.Configuration.MyConfigurationManager.GetAppSettingValue("IPDiscount");
            lblInterest.Text = Resources.CarInsurance.InterestFree;
            if (ddlBrokerProvider.Text == "11")
            {
                ddlNoofInstallments.Items.Clear();
                ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));

                ddlCreditCard.Items.Clear();
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankCITI, "CITI"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankK, "KBANK"));

                ddlGGDiscount.Items.Clear();
                ddlGGDiscount.Items.Add(new ListItem("0" + " %", "0"));
            }
            else if (ddlBrokerProvider.Text == "29")
            {
                ddlNoofInstallments.Items.Clear();
                ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));

                ddlCreditCard.Items.Clear();
                //Yui@31/07/2014 Remove LMG
                //ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankBKK, "BKK"));
                //ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankKTC, "KTC"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankK, "KBANK"));

                //Yui@31/07/2014 Remove LMG
                //ddlGGDiscount.Items.Clear();
                //if (IPDiscount != string.Empty)
                //{
                //    ddlGGDiscount.Items.Add(new ListItem(IPDiscount.ToString() + " %", IPDiscount.ToString()));
                //}
                //ddlGGDiscount.Items.Add(new ListItem("0" + " %", "0"));
            }
            else if (ddlBrokerProvider.Text == "32")
            {
                if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11" || ddlBrokerCoverType.Text == "21")
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));

                    ddlGGDiscount.Items.Clear();
                    ddlGGDiscount.Items.Add(new ListItem("0" + " %", "0"));
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));

                    ddlGGDiscount.Items.Clear();
                    ddlGGDiscount.Items.Add(new ListItem("0" + " %", "0"));

                    //Yui@27Feb2015
                    //ddlPaymentOption.Items.Clear();
                    //ddlPaymentOption.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
                    //ddlPaymentOption.Items.Add(new ListItem(Resources.CarInsurance.AnnualPayment, "FP"));
                }

                ddlCreditCard.Items.Clear();
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankBKK, "BKK"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankCITI, "CITI"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankKTC, "KTC"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankAYA, "AYA"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.CentralCard, "CTRL"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.RobinsonCard, "RBSN"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.HomeproCard, "HPRO"));
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankK, "KBANK"));//Sakthi on 15 Nov 2012
            }
            else
            {
                ddlNoofInstallments.Items.Clear();
                ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));

                ddlCreditCard.Items.Clear();
                ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.BankK, "KBANK"));
            }
            ddlCreditCard.Items.Add(new ListItem(Resources.CarInsurance.CashInstallment, "CHINS"));
            ddlCreditCard_SelectedIndexChanged(null, null);
            //Yui@26/05/2014 : ddlCreditCard_SelectedIndexChanged already called the method
            //NoofInstallments_SelectedIndexChanged(null, null);
        }
    }

    private void LoadBrokerDefault() //Sop Create method and updated on 16 Nov 2012 from BKK
    {
        try
        {
            if (ddlGarageType.Text == "-1" || ddlBrokerCoverType.Text == "-1")
            {
                return;
            }

            if (ddlBrokerProvider.Text.Length > 0 && ddlGarageType.Text.Length > 0 && ddlBrokerCoverType.Text.Length > 0)
            {
                MyDatabase _myDB = new MyDatabase();

                string _strSelect = "Select TPBIA, TPBIP, TPPD, PAPassenger, MedicalExpense, BailBond, DEC, FireTheft, FloodCover " + 
                    "from tblCXBrokerDefaultBenefits ";
                _strSelect = _strSelect + " WHERE CXBrokerProviderId = " + ddlBrokerProvider.Text;
                _strSelect = _strSelect + " AND GarageType = " + ddlGarageType.Text;
                _strSelect = _strSelect + " AND InsuranceType = " + ddlBrokerCoverType.SelectedValue;

                DataTable _dtDefaultValues = new DataTable("tblDefault");
                _dtDefaultValues = _myDB.GetDataTable(_strSelect);

                if (_dtDefaultValues != null && _dtDefaultValues.Rows.Count > 0)
                {
                    if (_dtDefaultValues.Rows[0]["TPBIA"] != DBNull.Value)
                    {
                        txtTPBIA.Text = Convert.ToInt32(_dtDefaultValues.Rows[0]["TPBIA"].ToString()).ToString("#,000");
                    }

                    if (_dtDefaultValues.Rows[0]["TPBIP"] != DBNull.Value)
                    {
                        txtTPBIP.Text = Convert.ToInt32(_dtDefaultValues.Rows[0]["TPBIP"].ToString()).ToString("#,000");
                    }

                    if (_dtDefaultValues.Rows[0]["TPPD"] != DBNull.Value)
                    {
                        txtTPPD.Text = Convert.ToInt32(_dtDefaultValues.Rows[0]["TPPD"].ToString()).ToString("#,000");
                    }

                    if (_dtDefaultValues.Rows[0]["PAPassenger"] != DBNull.Value)
                    {
                        txtPA.Text = _dtDefaultValues.Rows[0]["PAPassenger"].ToString();
                    }

                    if (_dtDefaultValues.Rows[0]["MedicalExpense"] != DBNull.Value)
                    {
                        txtMED.Text = _dtDefaultValues.Rows[0]["MedicalExpense"].ToString();
                    }

                    if (_dtDefaultValues.Rows[0]["BailBond"] != DBNull.Value)
                    {
                        txtBailBond.Text = Convert.ToInt32(_dtDefaultValues.Rows[0]["BailBond"].ToString()).ToString("#,000");
                    }

                    if (_dtDefaultValues.Rows[0]["DEC"] != DBNull.Value)
                    {
                        txtDeductible.Text = _dtDefaultValues.Rows[0]["DEC"].ToString();
                    }
                    if (_dtDefaultValues.Rows[0]["FireTheft"] != DBNull.Value)
                    {
                        txtFireTheft.Text = _dtDefaultValues.Rows[0]["FireTheft"].ToString();
                    }
                    if (_dtDefaultValues.Rows[0]["FloodCover"] != DBNull.Value)
                    {
                        txtFloodCoverAmount.Text = _dtDefaultValues.Rows[0]["FloodCover"].ToString();
                    }
                }
            }
        }
        catch (Exception Ex)
        {
            lblPremiumMessage.Text = Ex.Message;
        }
    }

    protected void NoofInstallments_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            //Yui@31/07/2014 Remove LMG
            //if (ddlBrokerProvider.Text == "29")
            //{
            //    if (ddlCreditCard.Text != "KBANK" && ddlCreditCard.Text != "CHINS")
            //    {
            //        if (ddlNoofInstallments.Text == "4")
            //        {
            //            lblInterest.Text = "3.2 % " + Resources.CarInsurance.Interest;
            //        }
            //        else if (ddlNoofInstallments.Text == "6")
            //        {
            //            lblInterest.Text = "4.8 % " + Resources.CarInsurance.Interest;
            //        }
            //        else
            //        {
            //            lblInterest.Text = Resources.CarInsurance.InterestFree;
            //        }
            //    }
            //    else
            //    {
            //        lblInterest.Text = Resources.CarInsurance.InterestFree;
            //    }
            //}
            lblCHINSMessage.Text = "";
            if (ddlCreditCard.Text == "CHINS")
            {
                if (ddlNoofInstallments.Text == "2")
                {
                    lblCHINSMessage.Text = "(50 : 50)";
                }
                else if (ddlNoofInstallments.Text == "3")
                {
                    lblCHINSMessage.Text = "(40 : 30 : 30)";
                }
                else if (ddlNoofInstallments.Text == "4")
                {
                    lblCHINSMessage.Text = "(25 : 25 : 25 : 25)";
                }
            }
            //Changed on 15 Mar 2013 -- Start
            InstallmentsCalculation();
            //Changed on 15 Mar 2013 -- End
        }
        catch (Exception Ex)
        {
        }
    }

    //Sakthi on 03 Oct 2012 -- End

    protected void ddlCreditCard_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (ddlBrokerProvider.Text == "11")
            {
                if (ddlCreditCard.Text == "CITI")
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    //NoofInstallments_SelectedIndexChanged(null, null);
                }
                else
                {
                    string selectedIndex = ddlNoofInstallments.Text;
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    ddlNoofInstallments.SelectedIndex = ddlNoofInstallments.Items.IndexOf(ddlNoofInstallments.Items.FindByValue(selectedIndex));
                    //NoofInstallments_SelectedIndexChanged(null, null);
                }
            }

            //For K Bank 6 Months Installments -- 22 Oct 2012 -- Start
            decimal _AnnualPremium = 0;
            decimal _AnnualPremiumWOD = 0;
            if (!decimal.TryParse(txtAnnualPremium.Text, out _AnnualPremium))
            {
                _AnnualPremium = 0;
            }

            if (!decimal.TryParse(txtFinalAnnualPremiumNoDisc.Text, out _AnnualPremiumWOD))
            {
                _AnnualPremiumWOD = 0;
            }

            if (_AnnualPremiumWOD < 5000 && ddlCreditCard.Text == "CHINS")
            {
                ddlNoofInstallments.Items.Clear();
                ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));

                ddlGGDiscount.Items.Clear();
                ddlGGDiscount.Items.Add(new ListItem("0 %", "0"));
                //NoofInstallments_SelectedIndexChanged(null, null);
            }
            else if (_AnnualPremiumWOD >= 5000 && ddlCreditCard.Text == "CHINS")
            {
                Int32 intInstallVal = 0;
                intInstallVal = CheckCommencementDateforCashInstallment();
                if (intInstallVal == 0)
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));
                }
                else if (intInstallVal == 2)
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("2" + " " + Resources.CarInsurance.Installment, "2"));
                }
                else if (intInstallVal == 3)
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    ddlNoofInstallments.Items.Add(new ListItem("2" + " " + Resources.CarInsurance.Installment, "2"));
                }
                else if (intInstallVal == 4)
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    ddlNoofInstallments.Items.Add(new ListItem("2" + " " + Resources.CarInsurance.Installment, "2"));
                }

                ddlGGDiscount.Items.Clear();
                ddlGGDiscount.Items.Add(new ListItem("0 %", "0"));
                //NoofInstallments_SelectedIndexChanged(null, null);
            }
            else if (_AnnualPremiumWOD >= 15000 && ddlCreditCard.Text == "KBANK")
            {
                if (ddlNoofInstallments.Text == "3")
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("10" + " " + Resources.CarInsurance.Installment, "10"));
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    ddlNoofInstallments.SelectedIndex = ddlNoofInstallments.Items.IndexOf(ddlNoofInstallments.Items.FindByValue("3"));
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("10" + " " + Resources.CarInsurance.Installment, "10"));
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                }
            }
            else if (_AnnualPremiumWOD >= 10000 && ddlCreditCard.Text == "KBANK")
            {

                if (ddlBrokerProvider.Text == "32")
                {
                    if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11" || ddlBrokerCoverType.Text == "21")
                    {
                        if (ddlNoofInstallments.Text == "3")
                        {
                            ddlNoofInstallments.Items.Clear();
                            ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                            ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                            ddlNoofInstallments.SelectedIndex = ddlNoofInstallments.Items.IndexOf(ddlNoofInstallments.Items.FindByValue("3"));
                        }
                        else
                        {
                            ddlNoofInstallments.Items.Clear();
                            ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                            ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                        }
                    }
                    else
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));
                    }
                }
                else
                {
                    //Yui@31/07/2014 Remove LMG
                    //if (ddlBrokerProvider.Text == "29")
                    //{
                    //    string IPDiscount = CE.Configuration.MyConfigurationManager.GetAppSettingValue("IPDiscount");
                    //    ddlGGDiscount.Items.Clear();
                    //    if (IPDiscount != string.Empty)
                    //    {
                    //        ddlGGDiscount.Items.Add(new ListItem(IPDiscount.ToString() + " %", IPDiscount.ToString()));
                    //    }
                    //}

                    if (ddlNoofInstallments.Text == "3")
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                        ddlNoofInstallments.SelectedIndex = ddlNoofInstallments.Items.IndexOf(ddlNoofInstallments.Items.FindByValue("3"));
                    }
                    else
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    }
                }
                //NoofInstallments_SelectedIndexChanged(null, null);
            }
            else
            {
                if (ddlBrokerProvider.Text == "11")
                {
                    if (ddlCreditCard.Text == "CITI")
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        //NoofInstallments_SelectedIndexChanged(null, null);//Sakthi on 25 Oct 2012 -- Added
                    }
                    else if (ddlCreditCard.Text == "KBANK")
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                        //NoofInstallments_SelectedIndexChanged(null, null);
                    }
                }
                else if (ddlBrokerProvider.Text == "29")
                {
                    //Yui@31/07/2014 Remove LMG
                    //string IPDiscount = CE.Configuration.MyConfigurationManager.GetAppSettingValue("IPDiscount");
                    //ddlGGDiscount.Items.Clear();
                    //if (IPDiscount != string.Empty)
                    //{
                    //    ddlGGDiscount.Items.Add(new ListItem(IPDiscount.ToString() + " %", IPDiscount.ToString()));
                    //}
                    //ddlGGDiscount.Items.Add(new ListItem("0" + " %", "0"));

                    if (ddlCreditCard.Text == "KBANK")
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                        //NoofInstallments_SelectedIndexChanged(null, null);
                    }
                    else if (ddlNoofInstallments.Text == "6")
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                        //NoofInstallments_SelectedIndexChanged(null, null);
                    }
                    else
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        //NoofInstallments_SelectedIndexChanged(null, null);
                    }
                }
                else if (ddlBrokerProvider.Text == "32")
                {
                    if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11" || ddlBrokerCoverType.Text == "21")
                    {

                        if (ddlCreditCard.Text == "KBANK")
                        {
                            ddlNoofInstallments.Items.Clear();
                            ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                            //NoofInstallments_SelectedIndexChanged(null, null);
                        }
                        else
                        {
                            ddlNoofInstallments.Items.Clear();
                            ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                            //NoofInstallments_SelectedIndexChanged(null, null);
                        }

                    }
                    else
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));
                        //NoofInstallments_SelectedIndexChanged(null, null);
                    }
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    //NoofInstallments_SelectedIndexChanged(null, null);
                }
            }

            //Yui@26/05/2014
            NoofInstallments_SelectedIndexChanged(null, null);
        }
        catch (Exception Ex)
        {
        }
    }

    //Sakthi on 25 Oct 2012 -- Start
    public void SixMonthIstallMents()
    {

        decimal _AnnualPremium = 0;
        decimal _AnnualPremiumWOD = 0;
        if (!decimal.TryParse(txtAnnualPremium.Text, out _AnnualPremium))
        {
            _AnnualPremium = 0;
        }
        if (!decimal.TryParse(txtFinalAnnualPremiumNoDisc.Text, out _AnnualPremiumWOD))
        {
            _AnnualPremiumWOD = 0;
        }
        if (_AnnualPremiumWOD < 5000 && ddlCreditCard.Text == "CHINS")
        {
            ddlNoofInstallments.Items.Clear();
            ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));

        }
        else if (_AnnualPremiumWOD >= 5000 && ddlCreditCard.Text == "CHINS")
        {
            Int32 NoofInstall = CheckCommencementDateforCashInstallment();
            if (ddlNoofInstallments.Text == "4")
            {
                ddlNoofInstallments.Items.Clear();
                ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                ddlNoofInstallments.Items.Add(new ListItem("2" + " " + Resources.CarInsurance.Installment, "2"));
            }
            else if (ddlNoofInstallments.Text == "3")
            {
                if (NoofInstall > 3)
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                    ddlNoofInstallments.Items.Add(new ListItem("2" + " " + Resources.CarInsurance.Installment, "2"));
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    ddlNoofInstallments.Items.Add(new ListItem("2" + " " + Resources.CarInsurance.Installment, "2"));
                }
            }
            else if (ddlNoofInstallments.Text == "2")
            {
                if (NoofInstall > 3)
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("2" + " " + Resources.CarInsurance.Installment, "2"));
                    ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                }
                else if (NoofInstall > 2 && NoofInstall <= 3)
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("2" + " " + Resources.CarInsurance.Installment, "2"));
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("2" + " " + Resources.CarInsurance.Installment, "2"));
                }
            }
            else
            {
                ddlNoofInstallments.Items.Clear();
                ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));
            }
        }
        else if (_AnnualPremiumWOD >= 15000 && ddlCreditCard.Text == "KBANK")
        {
            string noIns = ddlNoofInstallments.SelectedValue;
            ddlNoofInstallments.Items.Clear();
            ddlNoofInstallments.Items.Add(new ListItem("10" + " " + Resources.CarInsurance.Installment, "10"));
            ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
            ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
            ddlNoofInstallments.SelectedIndex = ddlNoofInstallments.Items.IndexOf(ddlNoofInstallments.Items.FindByValue(noIns));
            //ddlNoofInstallments.SelectedIndex = ddlNoofInstallments.Items.IndexOf(ddlNoofInstallments.Items.FindByValue("3"));
            //if (ddlNoofInstallments.Text == "3")
            //{
            //    ddlNoofInstallments.Items.Clear();
            //    ddlNoofInstallments.Items.Add(new ListItem("10" + " " + Resources.CarInsurance.Installment, "10"));
            //    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
            //    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
            //    ddlNoofInstallments.SelectedIndex = ddlNoofInstallments.Items.IndexOf(ddlNoofInstallments.Items.FindByValue("3"));
            //}
            //else
            //{
            //    ddlNoofInstallments.Items.Clear();
            //    ddlNoofInstallments.Items.Add(new ListItem("10" + " " + Resources.CarInsurance.Installment, "10"));
            //    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
            //    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
            //}
        }
        else if (_AnnualPremiumWOD >= 10000 && ddlCreditCard.Text == "KBANK")
        {

            if (ddlBrokerProvider.Text == "32")
            {
                if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11" || ddlBrokerCoverType.Text == "21")
                {

                    if (ddlNoofInstallments.Text == "3")
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                        ddlNoofInstallments.SelectedIndex = ddlNoofInstallments.Items.IndexOf(ddlNoofInstallments.Items.FindByValue("3"));
                    }
                    else
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                        ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    }

                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));
                }
            }
            else
            {
                if (ddlNoofInstallments.Text == "3")
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    ddlNoofInstallments.SelectedIndex = ddlNoofInstallments.Items.IndexOf(ddlNoofInstallments.Items.FindByValue("3"));
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                }
            }

        }
        else
        {
            if (ddlBrokerProvider.Text == "11")
            {
                if (ddlCreditCard.Text == "CITI")
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                }
            }
            else if (ddlBrokerProvider.Text == "29")
            {
                if (ddlCreditCard.Text == "KBANK")
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                }
                else if (ddlNoofInstallments.Text == "6")
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("4" + " " + Resources.CarInsurance.Installment, "4"));
                    ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                }
            }
            else if (ddlBrokerProvider.Text == "32")
            {
                if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11" || ddlBrokerCoverType.Text == "21")
                {

                    if (ddlCreditCard.Text == "KBANK")
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
                    }
                    else
                    {
                        ddlNoofInstallments.Items.Clear();
                        ddlNoofInstallments.Items.Add(new ListItem("6" + " " + Resources.CarInsurance.Installment, "6"));
                    }

                }
                else
                {
                    ddlNoofInstallments.Items.Clear();
                    ddlNoofInstallments.Items.Add(new ListItem("0" + " " + Resources.CarInsurance.Installment, "0"));
                }
            }
            else
            {
                ddlNoofInstallments.Items.Clear();
                ddlNoofInstallments.Items.Add(new ListItem("3" + " " + Resources.CarInsurance.Installment, "3"));
            }
        }


    }

    protected void csvDeductibleValid_ServerValidate(object source, ServerValidateEventArgs args)
    {
        args.IsValid = true;
        float _deductible = 0.0f;
        if (ddlBrokerProvider.Text == "43" && ddlBrokerCoverType.Text == "31" && txtUserTypeId.Text == "1001")
        {
            if (txtDeductible.Text.Trim() != "")
            {
                if (!float.TryParse(txtDeductible.Text, out _deductible))
                {
                    _deductible = 0.0f;
                }
                if (_deductible > 0)
                {
                    args.IsValid = true;
                }
                else
                {
                    args.IsValid = false;
                }
            }
            else
            {
                args.IsValid = false;
            }
        }
    }

    private void LoadgentbyAdmin()
    {
        try
        {
            MyDatabase _db = new MyDatabase();
            DataTable _dt = new DataTable("tblList");
            string _spName = "sprocCXCRMGetAgentList";

            SortedList paraList = new SortedList();
            paraList.Add("@AgentID", Session[General.UserId].ToString());
            _dt = _db.GetDataTableBySP(_spName, paraList);

            ddlAgentbyAdmin.Items.Clear();
            
            if (_dt != null && _dt.Rows.Count > 0)
            {
                ddlAgentbyAdmin.DataSource = _dt;
                ddlAgentbyAdmin.DataTextField = "FULLNAME";
                ddlAgentbyAdmin.DataValueField = "CEID";
                ddlAgentbyAdmin.DataBind();
            }
            ddlAgentbyAdmin.Items.Add(new ListItem("None", "0"));
        }
        catch (Exception ex)
        {
        }
    }

    #region GetCustomerType
    //public Int16 GetCustomerType(string RefCEUserId)
    //{
    //    Int16 IsThai = 1;
    //    MyDatabase _db = new MyDatabase();
    //    string strSql = "SELECT IsThai = CASE WHEN Ninfo7 IS NULL THEN 1 ELSE Ninfo7 END FROM tblCEUsrProfile WHERE RefCEUserId = " + RefCEUserId;
    //    object _result = _db.ExecuteScalarSqlStatement(strSql);
    //    if (_result != null)
    //    {
    //        if (!Int16.TryParse(_result.ToString(), out IsThai))
    //        {
    //            IsThai = 1;
    //        }
    //    }
    //    return IsThai;
    //}
    #endregion

    private void InstallmentsCalculation()
    {
        SixMonthIstallMents();
        lblTitleLastInstallWDDesc.Text = "";
        lblTitleLastInstallWODDesc.Text = "";
        decimal _annualPremium = 0;
        decimal _annualPremiumNoDisc = 0;
        decimal _InstallmentInterest = 0;
        decimal _InstallmentannualPremiumWD = 0;
        decimal _InstallmentAmountWD = 0;
        decimal _InstallmentLastMonthAmountWD = 0;
        decimal _InstallmentannualPremiumWOD = 0;
        decimal _InstallmentAmountWOD = 0;
        decimal _InstallmentLastMonthAmountWOD = 0;

        string _strannualPremium = txtFinalAnnualPremium.Text.Replace(",", "");
        string _strannualPremiumNoDisc = txtFinalAnnualPremiumNoDisc.Text.Replace(",", "");
        if (!decimal.TryParse(_strannualPremium, out _annualPremium))
        {
            _annualPremium = 0;
        }
        if (!decimal.TryParse(_strannualPremiumNoDisc, out _annualPremiumNoDisc))
        {
            _annualPremiumNoDisc = 0;
        }

        if (_annualPremiumNoDisc < 5000 && ddlCreditCard.Text == "CHINS")
        {
            _InstallmentannualPremiumWD = 0;
            _InstallmentAmountWD = 0;
            _InstallmentLastMonthAmountWD = 0;
            _InstallmentannualPremiumWOD = 0;
            _InstallmentAmountWOD = 0;
            _InstallmentLastMonthAmountWOD = 0;
        }
        else if (_annualPremiumNoDisc >= 5000 && ddlCreditCard.Text == "CHINS")
        {
            _InstallmentannualPremiumWD = _annualPremium;
            _InstallmentannualPremiumWOD = _annualPremiumNoDisc;
        }
        else if (_annualPremium >= 4000 && ddlBrokerProvider.Text == "29")
        {
            if (ddlNoofInstallments.Text == "4")
            {
                _InstallmentInterest = Convert.ToDecimal(1.032);
            }
            else if (ddlNoofInstallments.Text == "6")
            {
                _InstallmentInterest = Convert.ToDecimal(1.048);
            }
            if (ddlCreditCard.Text == "KBANK")
            {
                _InstallmentannualPremiumWD = _annualPremium;
                _InstallmentannualPremiumWOD = _annualPremiumNoDisc;
            }
            else
            {
                _InstallmentannualPremiumWD = (_annualPremium * _InstallmentInterest);
                _InstallmentannualPremiumWOD = (_annualPremiumNoDisc * _InstallmentInterest);
            }
        }
        else if (_annualPremiumNoDisc >= 4000 && ddlBrokerProvider.Text == "32")
        {
            if (ddlBrokerCoverType.Text == "10" || ddlBrokerCoverType.Text == "11" || ddlBrokerCoverType.Text == "21")
            {
                _InstallmentannualPremiumWD = _annualPremiumNoDisc;
                _InstallmentannualPremiumWOD = _annualPremiumNoDisc;
            }
            else
            {
                _InstallmentannualPremiumWD = 0;
                _InstallmentAmountWD = 0;
                _InstallmentLastMonthAmountWD = 0;
                _InstallmentannualPremiumWOD = 0;
                _InstallmentAmountWOD = 0;
                _InstallmentLastMonthAmountWOD = 0;
            }
        }
        else if (_annualPremiumNoDisc >= 4000)
        {
            _InstallmentannualPremiumWD = _annualPremiumNoDisc;
            _InstallmentannualPremiumWOD = _annualPremiumNoDisc;
        }
        else
        {
            _InstallmentannualPremiumWD = 0;
            _InstallmentAmountWD = 0;
            _InstallmentLastMonthAmountWD = 0;
            _InstallmentannualPremiumWOD = 0;
            _InstallmentAmountWOD = 0;
            _InstallmentLastMonthAmountWOD = 0;
        }

        Int32 _Installments = Convert.ToInt32(ddlNoofInstallments.Text);
        Int32 _Install = _Installments - 1;
        decimal _TotalInstallMentWOD = 0;
        //decimal _TotalInstallMentWD = 0;

        //Yui@31/07/2014 Remove LMG
        //if (ddlBrokerProvider.Text == "29" && ddlCreditCard.Text != "CHINS")
        //{
        //    if (_InstallmentannualPremiumWD > 0 && _Installments > 0)
        //    {
        //        _InstallmentAmountWD = Math.Ceiling(Convert.ToDecimal(_InstallmentannualPremiumWD / _Installments));
        //        _TotalInstallMentWD = Convert.ToDecimal(_InstallmentAmountWD * _Install);
        //        _InstallmentLastMonthAmountWD = Convert.ToDecimal(_InstallmentannualPremiumWD - _TotalInstallMentWD);
        //    }
        //}
        //else
        //{

        //_TotalInstallMentWD = 0;
        _InstallmentAmountWD = 0;
        _InstallmentLastMonthAmountWD = 0;
        //}

        if (_InstallmentannualPremiumWOD > 0 && _Installments > 0)
        {
            if (ddlCreditCard.Text == "CHINS")
            {
                decimal tempInstall = 0;
                if (_Installments == 2)
                {
                    tempInstall = Convert.ToDecimal(_InstallmentannualPremiumWOD / 10);
                    _TotalInstallMentWOD = Math.Ceiling(Convert.ToDecimal(tempInstall * 5));
                    _InstallmentAmountWOD = (_InstallmentannualPremiumWOD - _TotalInstallMentWOD);
                    _InstallmentLastMonthAmountWOD = _TotalInstallMentWOD;
                }
                else if (_Installments == 3)
                {
                    tempInstall = Convert.ToDecimal(_InstallmentannualPremiumWOD / 10);
                    _TotalInstallMentWOD = Math.Ceiling(Convert.ToDecimal(tempInstall * 3));
                    _InstallmentAmountWOD = (_InstallmentannualPremiumWOD - (_TotalInstallMentWOD * 2));
                    _InstallmentLastMonthAmountWOD = _TotalInstallMentWOD;
                }
                else if (_Installments == 4)
                {
                    tempInstall = Convert.ToDecimal(_InstallmentannualPremiumWOD / 4);
                    _TotalInstallMentWOD = Math.Ceiling(tempInstall);
                    _InstallmentAmountWOD = (_InstallmentannualPremiumWOD - (_TotalInstallMentWOD * 3));
                    _InstallmentLastMonthAmountWOD = _TotalInstallMentWOD;
                }
            }
            else
            {
                _InstallmentAmountWOD = Math.Ceiling(Convert.ToDecimal(_InstallmentannualPremiumWOD / _Installments));
                _TotalInstallMentWOD = Convert.ToDecimal(_InstallmentAmountWOD * _Install);
                _InstallmentLastMonthAmountWOD = Convert.ToDecimal(_InstallmentannualPremiumWOD - _TotalInstallMentWOD);
            }
        }

        //Yui@31/07/2014 Remove LMG
        //if (ddlBrokerProvider.Text == "29" && ddlCreditCard.Text != "CHINS")
        //{
        //    lblTotalGrossPremiumWD.Text = _InstallmentannualPremiumWD.ToString("#0.00");
        //}
        //else
        //{
            lblTotalGrossPremiumWD.Text = Resources.CarInsurance.NoDiscount;
        //}

        lblFirstInstallmentWD.Text = _InstallmentAmountWD.ToString("#0.00");
        lblLastInstallmentWD.Text = _InstallmentLastMonthAmountWD.ToString("#0.00");
        lblTotalGrossPremiumWOD.Text = _InstallmentannualPremiumWOD.ToString("#0.00");
        lblFirstInstallmentWOD.Text = _InstallmentAmountWOD.ToString("#0.00");
        lblLastInstallmentWOD.Text = _InstallmentLastMonthAmountWOD.ToString("#0.00");
        if (ddlCreditCard.Text == "CHINS")
        {
            lblTitleFirstInstallWD.Text = Resources.CarInsurance.Installment;
            lblTitleFirstInstallWOD.Text = Resources.CarInsurance.Installment;
            lblTitleLastInstallWD.Text = Resources.CarInsurance.Installment;
            lblTitleLastInstallWOD.Text = Resources.CarInsurance.Installment;
            if (_Installments == 2)
            {
                lblTitleLastInstallWDDesc.Text = "(Last " + Resources.CarInsurance.Month + ")";
                lblTitleLastInstallWODDesc.Text = "(Last " + Resources.CarInsurance.Month + ")";
            }
            else if (_Installments == 3)
            {
                lblTitleLastInstallWDDesc.Text = "(Last 2 " + Resources.CarInsurance.Month + ")";
                lblTitleLastInstallWODDesc.Text = "(Last 2 " + Resources.CarInsurance.Month + ")";
            }
            else if (_Installments == 3)
            {
                lblTitleLastInstallWDDesc.Text = "(Last 3 " + Resources.CarInsurance.Months + ")";
                lblTitleLastInstallWODDesc.Text = "(Last 3 " + Resources.CarInsurance.Months + ")";
            }

            lblFirstInstallmentWDdesc.Text = "(1st " + Resources.CarInsurance.Month + ")";
            lblFirstInstallmentWODdesc.Text = "(1st " + Resources.CarInsurance.Month + ")";
        }
        else
        {
            lblTitleFirstInstallWD.Text = Resources.CarInsurance.Installment;
            lblTitleFirstInstallWOD.Text = Resources.CarInsurance.Installment;
            lblTitleLastInstallWD.Text = Resources.CarInsurance.LastMonthInstallment;
            lblTitleLastInstallWOD.Text = Resources.CarInsurance.LastMonthInstallment;

            lblFirstInstallmentWDdesc.Text = "(1 " + Resources.CarInsurance.To + " " + _Install.ToString() + " " + Resources.CarInsurance.Months + ")";
            lblFirstInstallmentWODdesc.Text = "(1 " + Resources.CarInsurance.To + " " + _Install.ToString() + " " + Resources.CarInsurance.Months + ")";
        }
    }

    protected void txtFinalAnnualPremium_TextChanged(object sender, EventArgs e)
    {
        try
        {
            InstallmentsCalculation();
            ShowTescoAmount();
        }
        catch (Exception Ex)
        {
            lblPremiumError.Text = Ex.Message;
            Ex = null;
        }
    }

    protected void txtFinalAnnualPremiumNoDisc_TextChanged(object sender, EventArgs e)
    {
        try
        {
            InstallmentsCalculation();
        }
        catch (Exception Ex)
        {
            lblPremiumError.Text = Ex.Message;
            Ex = null;
        }
    }

    private bool GGSpecialPremiumValidation()
    {
        bool _IsValid = false;
        try
        {
            if (txtGG.Text.Trim() == "GGSPECIAL")
            {
                MyDatabase _db = new MyDatabase();
                DataTable _dtSelect = new DataTable();
                string _strSelect = "SELECT CASE WHEN LEN(CD.Info16) > 0 THEN CD.Info16 ELSE CP.NCDPercent END AS NCDPercent "
                               + " FROM tblCarPolicy CP INNER JOIN tblCarDetailTH CD ON CD.CarId = CP.CECarId "
                               + " WHERE CP.RefCEUserId = " + txtCustomerId.Text + " AND CP.CECarId= " + txtCarId.Text;
                _dtSelect = _db.GetDataTable(_strSelect);
                if (_dtSelect.Rows.Count > 0 && _dtSelect.Rows[0]["NCDPercent"] != DBNull.Value != null && _dtSelect.Rows[0]["NCDPercent"].ToString() != string.Empty)
                {
                    if (_dtSelect.Rows[0]["NCDPercent"].ToString().Trim() == "50")
                    {
                        _IsValid = true;
                    }
                }
            }
            else
            {
                _IsValid = true;
            }
        }
        catch (Exception ex)
        {
            _IsValid = false;
        }
        return _IsValid;
    }

    private Int32 CheckCommencementDateforCashInstallment()
    {
        try
        {
            TimeSpan ts;
            Int32 days = 0;
            Int32 Installment = 0;
            DateTime _dtCoverCommDate = dateTimeNow;
            if (DateTime.TryParse(lblEditCoverCommencementDate.Text, out _dtCoverCommDate))
            {
                DateTime _dtNow = new DateTime(dateTimeNow.Year, dateTimeNow.Month, dateTimeNow.Day);

                ts = (_dtCoverCommDate.Date - _dtNow.Date);
                days = ts.Days;

                //Start 19 Jan 2015
                if (int.Parse(dateTimeNow.ToString("yyyyMMdd")) >= 20150119)
                {
                    if (days < 60)
                    {
                        Installment = 2;
                    }
                    else if (days >= 60 && days <= 90)
                    {
                        Installment = 3;
                    }
                    else if (days > 90)
                    {
                        Installment = 4;
                    }
                    else
                    {
                        Installment = 0;
                    }
                }
                else
                {
                    if (days > 30 && days <= 60)
                    {
                        Installment = 2;
                    }
                    else if (days > 60 && days <= 90)
                    {
                        Installment = 3;
                    }
                    else if (days > 90)
                    {
                        Installment = 4;
                    }
                    else
                    {
                        Installment = 0;
                    }
                }
            }
            else
            {
                Installment = 0;
            }
            return Installment;
        }
        catch (Exception ex)
        {
            return 0;
        }
    }

    public Int64 UpdateUsedLeadStatus(Int64 CarId, Int64 AgentId)
    {
        MyDatabase _db = new MyDatabase();
        Int64 _result = -1;
        string _spName = "sprocReportsAgentLeadUsedStatusUpdateSelectItem";
        SortedList _sPara = new SortedList();
        #region Parameter
        _sPara.Add("@CarId", CarId);
        _sPara.Add("@AgentId", AgentId);
        #endregion

        _result = _db.ExecuteSP(_spName, _sPara);
        return _result;
    }

    #region Selected Email Quote (Excel only)

    //OnClientClick="return SendOnlineQuotationConfirm();"
    protected void btnOnlineSendQuotation_Click(object sender, EventArgs e)
    {
        try
        {
            Page.Validate("sendonlinequotation");
            if (Page.IsValid)
            {
                Int16 IsThai = 1;
                if (chkExcelEng.Checked) IsThai = 0;

                if (IsThai == 1)
                {
                    Session["Language"] = "th-TH";
                }
                else
                {
                    Session["Language"] = "en-US";
                }

                if (grdExcelSelect.Rows.Count > 0 && grdExcelSelect.Rows.Count <= 4)
                {
                    String selectedCulture = CE.Global.General.SetCulture();
                    base.InitializeCulture();
                }
                else if (grdExcelSelect.Rows.Count > 4)
                {
                    lblOnlineSendQuotationMessage.Text = Resources.CarInsuranceResultPage.Email4Quote;
                    return;
                }
                else
                {
                    return;
                }

                //Yui@5/2/2015
                //GGPremiumListPDFOutput _nonGGPdf = CreateGGPDFObject();
                NonGGPremiumListPDFOutput _nonGGPdf = CreateGGPDFObject();
                string _fileName = _nonGGPdf.GeneratePDF(Session["Language"].ToString(), chkIsPromotion.Checked);
                if (_fileName != string.Empty)
                {

                    FileInfo file = new System.IO.FileInfo(_fileName);
                    BrokerPremiumDB _premiumDB = new BrokerPremiumDB();

                    if (file.Exists)
                    {
                        string[] _file = new string[1];
                        _file[0] = _fileName;

                        string _toemail = txtOnlineConfirmEmail.Text.Trim().ToLower();//30 Apr 2013
                        string _ccemail = string.Empty;
                        if (Session[General.UserRole].ToString() == "100")
                        {
                            _ccemail += Session[General.SMTPReplyTo].ToString();
                        }

                        string _bccemail = CE.Configuration.MyConfigurationManager.GetAppSettingValue("ADMIN");
                        string _customerName = lblName.Text + " " + lblLastName.Text;
                        string _emailTitle = string.Empty;
                        #region Old
                        //string mailBody = "";
                        //string imgUrl = "http://" + CE.Configuration.MyConfigurationManager.GetAppSettingValue("LogoPath");
                        //if (IsThai == 1)
                        //{
                        //    _emailTitle = "GluayGluay.com: ใบเสนอราคาประกันรถยนต์ คุณ " + lblName.Text + " "; //30 Apr 2013 +lblDispCarPlate.Text;
                        //    mailBody = @"เรียน คุณ <strong>" + _customerName + "</strong><br/><br/>" +
                        //    "<a href='http://www.gluaygluay.com'>GluayGluay.com</a> ขอส่งใบเสนอราคาแบบประกันรถยนต์ให้คุณ " + _customerName + " ได้ทำการเปรียบเทียบและตัดสินใจ<br/> " +
                        //    "หากท่านต้องการที่จะซื้อหรือต้องการสอบถามรายละเอียดเพิ่มเติม กรุณาติดต่อ <strong>" + Session[General.UserName] + "</strong> ได้ที่หมายเลขโทรศัพท์ <strong>" + Session[General.UserPhoneNo].ToString() + "</strong>";

                        //    if (Session[General.UserGender] == null)
                        //    {
                        //        mailBody += " ขอบพระคุณค่ะ <br/>";
                        //    }
                        //    else if (Session[General.UserGender].ToString() == "M")
                        //    {
                        //        mailBody += " ขอบพระคุณครับ <br/>";
                        //    }
                        //    else
                        //    {
                        //        mailBody += " ขอบพระคุณค่ะ <br/>";
                        //    }

                        //    mailBody += "<br/>ขอแสดงความนับถือ<br/>" +
                        //    "<img src='" + imgUrl + "' alt='GluayGluay' width='120' height='100' /><br/>" +
                        //    "<br/><strong><a href='http://www.gluaygluay.com'>GluayGluay.com</a> Support Team</strong><br/>" +
                        //        //Company Name changed
                        //    "บริษัท คอมแพร์เอ็กซ์เพรส นายหน้าประกันภัย (ประเทศไทย) จำกัด<br/>" +
                        //    "เลขทะเบียนนายหน้าประกันวินาศภัยนิติบุคคล เลขที่ ว00016/2553<br/>" +
                        //    "ชั้น 42 อาคารยูไนเต็ด เซ็นเตอร์<br/>" +
                        //    "เลขที่ 323 ถนนสีลม แขวงสีลม เขตบางรัก กรุงเทพฯ 10500<br/>" +
                        //    "โทร. 02-268-8222 โทรสาร 02-266-6339<br/>" +
                        //    "อีเมล์: support@gluaygluay.com<br/>" +
                        //    "กด Like เพื่อติดตามเราได้ใน Facebook: www.facebook.com/GGmotor";
                        //}
                        //else if (IsThai == 0)
                        //{
                        //    _emailTitle = "Car Insurance quotation  from gluaygluay.com for " + lblName.Text + " ";//30 Apr 2013 +lblDispCarPlate.Text;
                        //    mailBody = @"Dear <strong>" + _customerName + "</strong><br/><br/>" +
                        //    "<a href='http://www.gluaygluay.com'>Gluaygluay.com</a> would like to send you the quotation of your car insurance for compare and consider " +
                        //    "If you would like to buy or would like to get any further information kindly contact <strong>" + Session[General.UserName] + "</strong> at our hotline number <strong>" + Session[General.UserPhoneNo].ToString() + "</strong>, thank you very much.";

                        //    mailBody += "<br/>With best regards,<br/>" +
                        //    "<img src='" + imgUrl + "' alt='GluayGluay' width='120' height='100' /><br/>" +
                        //    "<br/><strong><a href='http://www.gluaygluay.com'>Gluaygluay.com</a> Support Team</strong><br/>" +
                        //    "Comparexpress Insurance Broker ( Thailand ) Ltd,<br/>" +
                        //    "License number  ว00016/2553<br/>" +
                        //    "42nd Floor, United Center Building,<br/>" +
                        //    "323 Silom Road, Bangrak, Bangkok 10500<br/>" +
                        //    "Tel : 02-268-8222 , Fax : 02-266-6339" +
                        //    "Email : support@gluaygluay.com<br/>" +
                        //    "Please click like us to follow all activities at facebook : www.facebook.com/GGmotor";
                        //}
                        #endregion

                        //string imgUrl = "http://" + CE.Configuration.MyConfigurationManager.GetAppSettingValue("LogoPath");
                        string imgUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("CRMPath") + "/";

                        StringBuilder strMailBody = new StringBuilder();
                        strMailBody.Append(@"<html>
                            <head>
                            <meta charset='utf-8'>
                            <title>GluayGluay</title>
                            <style>
                            body {
	                            margin-left: 0px;
	                            margin-top: 0px;
	                            margin-right: 0px;
	                            margin-bottom: 0px;
	                            font-family: tahoma, Arial, sans-serif;
	                            font-size: 14px;
	                            color: #4F4356 ;
	                            background-repeat: repeat-x;
	                            background-color: #fff;
	                            text-decoration: none;
                            }
                            a:link  {text-decoration:none; color:#0674DB;}
                            hr{display: block; height: 1px;
                                border: 0; border-top: 1px solid #ccc;
                                margin: 1em 0; padding: 0;}
	                            .line-height{line-height:20px;}
	                            .table-txt{padding-left:5px;}
                            </style>
                            </head><body>
                            <div class='email-containter'>
                            <div class='email-banner'></div>
                            <div class='email-text'>
                            <table width='800' border='0' align='center' cellpadding='0' cellspacing='0'>
                            <tr>
                            <td height='653' align='right' valign='bottom' bgcolor='#FFFFFF'>
                            <table width='800' height='100' border='0' cellspacing='0' cellpadding='0'>");
                        strMailBody.Append("<tr><td><span class='email-banner'><img src='" + imgUrl + "images/email-header.jpg' width='800' height='100' alt=''/></span></td>");
                        strMailBody.Append(@"</tr>
                            </table>
                            <table width='800' border='0' align='center' cellpadding='0' cellspacing='0'>
                            <tr>
                                <td width='672' align='left' valign='top' bgcolor='#FFFFFF'>
                            <table border='0' cellspacing='0' cellpadding='0'>
                            <tr>
                            <td align='left'>");
                        string mailBody = strMailBody.ToString();
                        if (IsThai == 1)
                        {
                            // "Khun. " + _customerName + ", License Plate: " + txtLicensePlate.Text + " Quotation at " + DateTime.Now.ToString("dd/MMM/yyyy");
                            _emailTitle = "GluayGluay.com: ใบเสนอราคาประกันรถยนต์ คุณ " + lblName.Text + " " + txtEditLicensePlate.Text;
                            mailBody += @"<p>เรียน คุณ <strong>" + _customerName + "</strong><br/></p>" +
                            "<p style=\"text-align: justify\"><a href='http://www.gluaygluay.com'>GluayGluay.com</a> ขอส่งใบเสนอราคาแบบประกันรถยนต์ให้คุณ " + _customerName + " ได้ทำการเปรียบเทียบและตัดสินใจ<br/> " +
                            "หากท่านต้องการที่จะซื้อหรือต้องการสอบถามรายละเอียดเพิ่มเติม กรุณาติดต่อ <strong>" + Session[General.UserName] + "</strong> ได้ที่หมายเลขโทรศัพท์ <strong>" + Session[General.UserPhoneNo].ToString() + "</strong>";
                            mailBody += " ขอบพระคุณค่ะ <br/></p>";

                            mailBody += "</td></tr><tr><td align=\"left\">";
                            mailBody += "<br/>ขอแสดงความนับถือ<br/></td></tr></table><hr><p>" +
                            "<br/><strong><a href='http://www.gluaygluay.com'>GluayGluay.com</a> Support Team</strong><br/>" +
                                //Company Name changed
                            "บริษัท คอมแพร์เอ็กซ์เพรส นายหน้าประกันภัย (ประเทศไทย) จำกัด<br/>" +
                            "เลขทะเบียนนายหน้าประกันวินาศภัยนิติบุคคล เลขที่ ว00016/2553<br/>" +
                            "42nd Floor, United Center Building,<br/>" +
                            "323 Silom Road, Bangrak, Bangkok 10500</p>" +
                            "<p>โทร. 02-268-8222 <br>โทรสาร 02-266-6339<br/>" +
                            "<a href=\"mailto:support@gluaygluay.com\">support@gluaygluay.com</a></p></td>" +
                            "</tr></table><hr>";
                        }
                        else if (IsThai == 0)
                        {
                            _emailTitle = "Car Insurance quotation  from gluaygluay.com for " + lblName.Text + " " + txtEditLicensePlate.Text;
                            mailBody += @"<p>Dear <strong>" + _customerName + "</strong><br/></p>" +
                            "<p style=\"text-align: justify\"><a href='http://www.gluaygluay.com'>Gluaygluay.com</a> would like to send you the quotation of your car insurance for compare and consider " +
                            "If you would like to buy or would like to get any further information kindly contact <strong>" + Session[General.UserNameEN] + "</strong> at our hotline number <strong>" + Session[General.UserPhoneNoEN].ToString() + "</strong>, thank you very much.</p>";

                            mailBody += "</td></tr><tr><td align=\"left\">";
                            mailBody += "<br/>With best regards,<br/></td></tr></table><hr><p>" +
                            "<br/><strong><a href='http://www.gluaygluay.com'>Gluaygluay.com</a> Support Team</strong><br/>" +
                            "Comparexpress Insurance Broker ( Thailand ) Ltd,<br/>" +
                            "License number  ว00016/2553<br/>" +
                            "42nd Floor, United Center Building,<br/>" +
                            "323 Silom Road, Bangrak, Bangkok 10500</p>" +
                            "<p>Tel : 02-268-8222 , Fax : 02-266-6339<br/>" +
                            "<a href=\"mailto:support@gluaygluay.com\">support@gluaygluay.com</a></p></td>" +
                            "</tr></table><hr>";
                        }

                        string YearEn = dateTimeNow.Year.ToString();
                        strMailBody = new StringBuilder();
                        strMailBody.Append(@"<table width='300' border='0' align='center' cellpadding='0' cellspacing='0'><tr>");
                        strMailBody.Append("<td width='44' style='text-align: center'><a href='https://www.facebook.com/GGmotor'><img src='" + imgUrl + "images/icons/fb-big.png' width='44' height='42' alt=''/></a></td>");
                        strMailBody.Append("<td width='44' style='text-align: center'><a href='https://plus.google.com/+Gluaygluay/posts'><img src='" + imgUrl + "images/icons/g-plus-big.png' width='44' height='42' alt=''/></a></td>");
                        strMailBody.Append("<td width='44' style='text-align: center'><a href='https://www.youtube.com/channel/UCZ4gMtlXymBHxvcXO2cR1vA'><img src='" + imgUrl + "images/icons/youtube-big.png' width='44' height='42' alt=''/></a></td>");
                        strMailBody.Append("<td width='44' style='text-align: center'><a href='http://iconosquare.com/ggmotor'><img src='" + imgUrl + "images/icons/instagram-big.png' width='44' height='42' alt=''/></a></td>");
                        strMailBody.Append("<td width='43' style='text-align: center'><a href='https://www.linkedin.com/company/-com-gluaygluay-com-'><img src='" + imgUrl + "images/icons/linkedin-big.png' width='44' height='42' alt=''/></a></td>");
                        strMailBody.Append(@"</tr>
                                         </table>
                                         <table width='800' height='100' border='0' cellspacing='0' cellpadding='0' background='images/email-footer.jpg'>
                                            <tr>
                                              <td><p style='text-align: center'><br><br>
                                                © " + YearEn + " gluaygluay.com. All rights reserved.<br>");
                        strMailBody.Append(Resources.EmailMessage.NoReply);
                        strMailBody.Append(@"</p></td></tr>
                                          </table></td>
                                          </tr>
                                        </table>
                                        </body>
                                        </html>");
                        mailBody += strMailBody.ToString();

                        bool _mailSendingStatus = false;

                        if (Session[General.SMTPAccountName].ToString().Contains("gluaygluay.com"))
                        {
                            _mailSendingStatus = MyMailManager.SendGGMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString(), _file);
                        }
                        else if (Session[General.SMTPAccountName].ToString().Contains("comparexpress.co.th"))
                        {
                            _mailSendingStatus = MyMailManager.SendGGMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString(), _file);
                        }
                        else if (Session[General.SMTPAccountName].ToString().Contains("gmail.com"))
                        {
                            _mailSendingStatus = MyMailManager.SendGGMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString(), _file);
                        }
                        else
                        {
                            _mailSendingStatus = MyMailManager.SendCXMailWithAttach(Session[General.SMTPAccountName].ToString(), Session[General.SMTPAuthCode].ToString(), _toemail, _ccemail, _bccemail, _emailTitle, mailBody, Session[General.SMTPReplyTo].ToString(), _file);
                        }

                        if (_mailSendingStatus)
                        {
                            if (_premiumDB.SaveQuotationEmail(Convert.ToInt32(txtCarId.Text),
                                Convert.ToInt64(txtCustomerId.Text),
                                Convert.ToInt64(Session[General.UserId].ToString()),
                                lblEditLicensePlate.Text,
                                txtOnlineConfirmEmail.Text, 1, _fileName) > 0)
                            {
                                lblOnlineSendQuotationMessage.Text = Resources.General.QuotationSent + " at " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm tt");
                            }
                            else
                            {
                                lblOnlineSendQuotationMessage.Text = Resources.General.QuotationSent + " Saving confirm email failed.";
                            }
                        }
                        else
                        {
                            lblOnlineSendQuotationMessage.Text = Resources.General.QuotationFailed;
                        }
                    }
                    else
                    {
                        lblOnlineSendQuotationMessage.Text = "PDF generating failed.";
                        lblOnlineSendQuotationMessage.Text += " " + Resources.General.QuotationFailed;
                    }
                }
                else
                {
                    lblOnlineSendQuotationMessage.Text = "PDF generating failed. No item found.";
                    lblOnlineSendQuotationMessage.Text += " " + Resources.General.QuotationFailed;
                }
            }
        }
        catch (Exception Ex)
        {
        }
        finally
        {
            if (lblLangOption.Text == "1")
            {
                Session["Language"] = "th-TH";
            }
            else
            {
                Session["Language"] = "en-US";
            }

            CE.Global.General.SetCulture();
            base.InitializeCulture();
        }
    }

    protected void btnSelectFromExcel_Click(object sender, EventArgs e)
    {
        if (hidQuoteEmailId.Value.Trim() != "")
        {
            MyDatabase _db = new MyDatabase();

            //Yui@5/2/2014
            string _spName = "";
            SortedList _sPara = new SortedList();
            //Save to temp
            _spName = "[sprocCarInsurancePremiumExcelUpdate]";
            _sPara.Add("@PremiumExcelIdList", hidQuoteEmailId.Value);
            _sPara.Add("@RefUserId", txtCustomerId.Text);
            _sPara.Add("@CarId", txtCarId.Text);
            _sPara.Add("@IsCTPL", chkCMI.Checked);

            _db.ExecuteNonSqlSP(_spName, _sPara);
            hidQuoteEmailId.Value = "";
            //*************
            lblOnlineSendQuotationMessage.Text = "Saved successfully.";

            SortedList _paraList = new SortedList();
            _paraList.Add("@CECarID", txtCarId.Text);
            _paraList.Add("@ProductType", "CIN");
            _paraList.Add("@RefCEUserId", "0");
            _paraList.Add("@LangOption", "1");

            DataTable _dtPremiumList = new DataTable("tblPremiumList");
            _dtPremiumList = _db.GetDataTableBySP("sprocCXOnlinePremiumSelectItemListExcel", _paraList);

            //Update in datagrid
            grdExcelSelect.DataSource = _dtPremiumList;
            grdExcelSelect.DataBind();
        }
        else
        {
            if (grdExcelSelect.Rows.Count < 1)
                return;
        }
    }

    protected void grdExcelSelect_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Select"))
        {
            int index = Convert.ToInt32(e.CommandArgument);
            DataKey myData = grdExcelSelect.DataKeys[index];

            Int64 _resultId = Convert.ToInt64(myData[0].ToString());
            PremiumSelectedFromExcel(_resultId);

            ddlBrokerProvider.Enabled = true;
        }
        else if (e.CommandName.Equals("DeleteRow"))
        {
            int index = Convert.ToInt32(e.CommandArgument);
            DataKey myData = grdExcelSelect.DataKeys[index];

            Int64 _resultId = Convert.ToInt64(myData[0].ToString());

            MyDatabase _db = new MyDatabase();
            SortedList _paraDel = new SortedList();
            _paraDel.Add("@CarId", txtCarId.Text);
            _paraDel.Add("@CITempResultId", _resultId);
            _db.ExecuteNonSqlSP("sprocProviderCarInsuranceClearExcel", _paraDel);

            SortedList _paraList = new SortedList();
            _paraList.Add("@CECarID", txtCarId.Text);
            _paraList.Add("@ProductType", "CIN");
            _paraList.Add("@RefCEUserId", "0");
            _paraList.Add("@LangOption", "1");

            DataTable _dtPremiumList = new DataTable("tblPremiumList");
            _dtPremiumList = _db.GetDataTableBySP("sprocCXOnlinePremiumSelectItemListExcel", _paraList);

            //Update in datagrid
            grdExcelSelect.DataSource = _dtPremiumList;
            grdExcelSelect.DataBind();
        }
    }

    //Yui@5/2/2015
    protected void btnExcelPremiumDownload_Click(object sender, EventArgs e)
    {
        if (grdExcelSelect.Rows.Count > 0)
        {
            NonGGPremiumListPDFOutput _nonGGPdf = CreateGGPDFObject();

            string _fileName = _nonGGPdf.GeneratePDF(Convert.ToString(Session["Language"]), chkIsPromotion.Checked);
            FileInfo file = new System.IO.FileInfo(_fileName);
            if (!file.Exists)
            {
                Response.StatusCode = 500;
                Response.End();
                return;
            }
            Response.Clear();
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetNoStore();
            Response.Cache.SetExpires(DateTime.MinValue);
            Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
            Response.AddHeader("Content-Length", file.Length.ToString());
            Response.ContentType = "application/octet-stream";
            Response.WriteFile(file.FullName);
            ApplicationInstance.CompleteRequest();
            Response.End();
        }
        else
        {
            ClientScript.RegisterStartupScript(btnPremiumDownload.GetType(), "DownloadPremiumAlert", "alert('No item to download!');", true);
        }
    }

    private NonGGPremiumListPDFOutput CreateGGPDFObject()
    {
        Int64 CECarId = Convert.ToInt64(txtCarId.Text);
        NonGGPremiumListPDFOutput _nonGGPdf = new NonGGPremiumListPDFOutput();

        _nonGGPdf.Title = "ใบเสนอราคาเบี้ยประกันรถยนต์";
        _nonGGPdf.Footer = "";//"For more information, please login to www.GluayGluay.com.";

        _nonGGPdf.CarId = txtCarId.Text;
        _nonGGPdf.CustomerName = lblName.Text + " " + lblLastName.Text;
        _nonGGPdf.CarPlateNumber = txtEditLicensePlate.Text;
        _nonGGPdf.Email = lblEmailAddress.Text;
        _nonGGPdf.DOB = lblDOB.Text;
        _nonGGPdf.Mobile = lblMobileNo.Text;
        _nonGGPdf.Gender = lblGender.Text;
        _nonGGPdf.Occupation = lblOccupation.Text;

        _nonGGPdf.CurrentInsurer = lblCurrentInsurer.Text;
        _nonGGPdf.CarMakeModel = lblCarMakeModel.Text;
        _nonGGPdf.CarModelYear = lblRegYear.Text;
        _nonGGPdf.AnyClaim = lblClaimInfo.Text;
        _nonGGPdf.CommnecementDate = ddlEditCoverCommencementDate.Text;
        lblEditCoverCommencementDate.Text = ddlEditCoverCommencementDate.Text;
        if (chkExtComDate.Checked && ddlExtComDate.SelectedIndex > 0)
        {
            _nonGGPdf.ExtComDate = ddlExtComDate.SelectedItem.Text;
        }

        _nonGGPdf.InsuranceType = lblInsuranceType.Text;
        _nonGGPdf.GarageType = lblGarageType.Text;
        _nonGGPdf.QuoteDateTime = lblRefModifiedDateTime.Text;
        _nonGGPdf.VehicleTypeUsage = lblVehicleType.Text;
        _nonGGPdf.IncludeCTPL = lblCTPL.Text;
        _nonGGPdf.NCB = ddlEditNCB.Text;

        Int16 IsThai = 1;
        if (chkExcelEng.Checked)
        {
            IsThai = 0;
        }

        if (IsThai == 1)
        {
            _nonGGPdf.AgentName = Session[General.UserName].ToString();
            _nonGGPdf.AgentContactNo = Session[General.UserPhoneNo].ToString();
        }
        else
        {
            _nonGGPdf.AgentName = Session[General.UserNameEN].ToString();
            _nonGGPdf.AgentContactNo = Session[General.UserPhoneNoEN].ToString();
        }

        _nonGGPdf.AgentEmail = Session[General.SMTPReplyTo].ToString();
        //if (ddlEditNamedDriver.Text != "0")
        //{
        //    _nonGGPdf.NamedDriver = ddlEditNamedDriver.Text;
        //}
        //else
        //{
        if (int.Parse(ddlNInsuranceType.SelectedValue) <= 11 && ddlNDriverAge.SelectedIndex > 1)
            _nonGGPdf.NamedDriver = Resources.Proposal.Yes;
        else
            _nonGGPdf.NamedDriver = Resources.Proposal.No;
        //}

        MyDatabase _db = new MyDatabase();
        SortedList _paraList = new SortedList();
        _paraList.Add("@CECarID", txtCarId.Text);
        _paraList.Add("@ProductType", "CIN");
        _paraList.Add("@RefCEUserId", "0");
        _paraList.Add("@LangOption", "1");

        DataTable _dtPremiumList = new DataTable("tblPremiumList");
        _dtPremiumList = _db.GetDataTableBySP("sprocCXOnlinePremiumSelectItemListExcel", _paraList);

        //Update in datagrid
        //grdExcelSelect.DataSource = _dtPremiumList;
        //grdExcelSelect.DataBind();

        if (_dtPremiumList != null)
        {
            _nonGGPdf.ResultGridTable = _dtPremiumList;

            _paraList.Clear();
            _paraList.Add("@AgentId", Session[General.UserId].ToString());
            DataTable _dtAgentList = new DataTable("tblAgentList");
            _dtAgentList = _db.GetDataTableBySP("sprocCXCRMAgentLicense", _paraList);
            if (_dtAgentList != null)
            {
                foreach (DataRow drAgentList in _dtAgentList.Rows)
                {
                    if (drAgentList["CEID"].ToString() == Session[General.UserId].ToString())
                    {
                        if (drAgentList["LicenseNo"] != DBNull.Value)
                            _nonGGPdf.AgentLicenseNo = drAgentList["LicenseNo"].ToString();
                    }
                    else
                    {
                        if (IsThai == 1)
                        {
                            _nonGGPdf.AgentSupervisor = drAgentList["AgentName"].ToString();
                        }
                        else
                        {
                            _nonGGPdf.AgentSupervisor = drAgentList["AgentNameEN"].ToString();
                        }

                        if (drAgentList["LicenseNo"] != DBNull.Value)
                            _nonGGPdf.AgentSupLicenseNo = drAgentList["LicenseNo"].ToString();
                    }
                }
            }

        }
        return _nonGGPdf;
    }

    //Yui@5/2/2015
    //private GGPremiumListPDFOutput CreateGGPDFObject()
    //{
    //    Int64 CECarId = Convert.ToInt64(txtCarId.Text);

    //    GGPremiumListPDFOutput _GGPdf = new GGPremiumListPDFOutput();
    //    _GGPdf.Title = "ใบเสนอราคาเบี้ยประกันรถยนต์";
    //    _GGPdf.Footer = "";//"For more information, please login to www.GluayGluay.com.";

    //    _GGPdf.CarId = txtCarId.Text;
    //    _GGPdf.CustomerName = lblName.Text + " " + lblLastName.Text;
    //    _GGPdf.CarPlateNumber = lblEditLicensePlate.Text; //30 Apr 2013
    //    _GGPdf.Email = lblEmailAddress.Text;
    //    _GGPdf.DOB = lblDOB.Text;
    //    _GGPdf.Mobile = lblMobileNo.Text;
    //    _GGPdf.Gender = lblGender.Text;
    //    _GGPdf.Occupation = lblOccupation.Text;

    //    _GGPdf.CurrentInsurer = lblCurrentInsurer.Text;
    //    _GGPdf.CarMakeModel = lblCarMakeModel.Text;
    //    _GGPdf.CarModelYear = lblRegYear.Text;
    //    _GGPdf.AnyClaim = lblClaimInfo.Text;
    //    _GGPdf.CommnecementDate = ddlEditCoverCommencementDate.Text;
    //    if (chkExtComDate.Checked && ddlExtComDate.SelectedIndex > 0)
    //    {
    //        _GGPdf.ExtComDate = ddlExtComDate.SelectedItem.Text;
    //    }

    //    _GGPdf.InsuranceType = lblInsuranceType.Text;
    //    _GGPdf.GarageType = lblGarageType.Text;
    //    _GGPdf.QuoteDateTime = lblRefModifiedDateTime.Text;
    //    _GGPdf.VehicleTypeUsage = lblVehicleType.Text;
    //    _GGPdf.IncludeCTPL = lblCTPL.Text; //30 Apr 2013
    //    _GGPdf.NCB = ddlEditNCB.Text + "%"; //30 Apr 2013
    //    _GGPdf.AgentName = Session[General.UserName].ToString();
    //    _GGPdf.AgentEmail = Session[General.SMTPReplyTo].ToString();
    //    _GGPdf.AgentContactNo = Session[General.UserPhoneNo].ToString();
    //    if (ddlEditNamedDriver.Text != "0")
    //    {
    //        _GGPdf.NamedDriver = ddlEditNamedDriver.Text;
    //    }
    //    else
    //    {
    //        _GGPdf.NamedDriver = Resources.Proposal.No;
    //    }


    //    MyDatabase _db = new MyDatabase();
    //    SortedList _paraList = new SortedList();
    //    _paraList.Add("@CECarID", txtCarId.Text);
    //    _paraList.Add("@ProductType", "CIN");
    //    _paraList.Add("@RefCEUserId", "0");
    //    if (chkExcelEng.Checked)
    //    {
    //        _paraList.Add("@LangOption", "1");
    //    }
    //    else
    //    {
    //        _paraList.Add("@LangOption", "2");
    //    }

    //    DataTable _dtPremiumList = new DataTable("tblPremiumList");
    //    _dtPremiumList = _db.GetDataTableBySP("sprocCXOnlinePremiumSelectItemListExcel", _paraList);
    //    if (_dtPremiumList != null)
    //    {
    //        _GGPdf.ResultGridTable = _dtPremiumList;
    //    }

    //    _paraList.Clear();
    //    _paraList.Add("@AgentId", Session[General.UserId].ToString());
    //    DataTable _dtAgentList = new DataTable("tblAgentList");
    //    _dtAgentList = _db.GetDataTableBySP("sprocCXCRMAgentLicense", _paraList);
    //    if (_dtAgentList != null)
    //    {
    //        foreach (DataRow drAgentList in _dtAgentList.Rows)
    //        {
    //            if (drAgentList["CEID"].ToString() == Session[General.UserId].ToString())
    //            {
    //                if (drAgentList["LicenseNo"] != DBNull.Value)
    //                    _GGPdf.AgentLicenseNo = drAgentList["LicenseNo"].ToString();
    //            }
    //            else
    //            {
    //                _GGPdf.AgentSupervisor = drAgentList["AgentName"].ToString();

    //                if (drAgentList["LicenseNo"] != DBNull.Value)
    //                    _GGPdf.AgentSupLicenseNo = drAgentList["LicenseNo"].ToString();
    //            }
    //        }
    //    }
    //    return _GGPdf;
    //}

    public Int64 UpdateCarResultSelectedItem(Int64 AgentId, Int64 CITempResultId, float TotalVMI, float CMI)
    {
        MyDatabase _db = new MyDatabase();
        Int64 _result = -1;
        string _spName = "sprocCXCRMCarResultUpdateSelectedItemByAgentExcel";

        SortedList _sPara = new SortedList();

        #region Parameter
        _sPara.Add("@AgentId", AgentId);
        _sPara.Add("@CITempResultId", CITempResultId);
        _sPara.Add("@TotalVMI", TotalVMI);
        _sPara.Add("@CMI", CMI);
        #endregion

        _result = _db.ExecuteSP(_spName, _sPara);

        return _result;
    }

    private string[] PremiumforOnlineResult(string[] INPremium, Int32 Discount, Int32 CTPL, string CTPLAmount)
    {
        string[] OUTPremium = new string[INPremium.Length];

        decimal _premium = 0;
        decimal _netPremium = 0;
        decimal _netPremiumround = 0;
        Int64 ProviderId = 0;
        decimal _ctpl = 0;
        string txtCarResultId = "0";
        string txtGrossPremium = "0";
        string txtVAT = "";
        string txtTax = "";
        string txtNetPremium = "";
        string lblTax = "0";
        string lblVAT = "0";
        string lblNetPremium = "0";
        string lblAnnualPremium = "0";
        if (!decimal.TryParse(CTPLAmount, out _ctpl))
        {
            _ctpl = 0;
        }
        for (int a = 0; a < INPremium.Length; a++)
        {
            string[] val = INPremium[a].Split('@');
            txtCarResultId = val[0].ToString();
            txtGrossPremium = val[1].ToString();
            ProviderId = Convert.ToInt64(val[2].ToString());
            if (decimal.TryParse(txtGrossPremium, out _premium) && ProviderId != 39)
            {
                decimal _grossPremium = _premium;
                _netPremium = _premium / 1.07M / 1.004M;
                _netPremium = Math.Floor(_netPremium);
                _netPremium = Math.Round(_netPremium);

                txtNetPremium = _netPremium.ToString("#0.00");
                decimal _tax = 0;
                _tax = Convert.ToDecimal(_netPremium * (0.4M / 100.0M));
                _tax = Math.Ceiling(_tax);
                if (_tax >= 1000)
                {
                    lblTax = _tax.ToString("#,000.00");
                }
                else
                {
                    lblTax = _tax.ToString("#0.00");
                }
                txtTax = _tax.ToString("#0.00");

                decimal _vat = 0;
                _vat = Convert.ToDecimal((_netPremium + _tax) * Convert.ToDecimal(7.0 / 100.0));
                if (_vat >= 1000)
                {
                    lblVAT = _vat.ToString("#,000.00");
                }
                else
                {
                    lblVAT = _vat.ToString("#0.00");
                }
                txtVAT = _vat.ToString("#0.00");

                _netPremium = _grossPremium - (_vat + _tax);
                if (_netPremium >= 1000)
                {
                    lblNetPremium = _netPremium.ToString("#,000.00");
                }
                else
                {
                    lblNetPremium = _netPremium.ToString("#0.00");
                }


                decimal _annualPremium = 0;
                decimal _annualPremiumNoDisc = 0;

                _annualPremiumNoDisc = _netPremium + _vat + _tax;
                _netPremiumround = Math.Round(_netPremium);
                _netPremiumround = Math.Floor(_netPremiumround);

                if (_annualPremiumNoDisc >= 5000 && Discount > 0) //16 May 2013 -- change amount 10000 to 5000
                {
                    decimal _discountAmount = Convert.ToDecimal((_netPremiumround * Convert.ToDecimal(Convert.ToDecimal(Discount) / 100.0M)));
                    _annualPremium = (_netPremiumround + _vat + _tax) - _discountAmount;
                }
                else
                {
                    _annualPremium = _netPremium + _vat + _tax;
                }

                if (_annualPremium >= 1000)
                {
                    lblAnnualPremium = _annualPremium.ToString("#,000.00");
                }
                else
                {
                    lblAnnualPremium = _annualPremium.ToString("#0.00");
                }


                OUTPremium[a] = txtCarResultId + "@" + _annualPremium.ToString("#0.00");
            }
            else
            {
                OUTPremium[a] = txtCarResultId + "@" + txtGrossPremium;
            }
        }

        return OUTPremium;
    }

    private string GetCTPLAmount(Int32 CC, string VehicleCode)
    {
        string _CTPLAmount = "0";
        if (CC <= 1500 && (VehicleCode == "110" || VehicleCode == "320"))
        {
            _CTPLAmount = "645.21";
        }
        else
        {
            _CTPLAmount = "967.28";
        }
        return _CTPLAmount;
    }

    #endregion

    #region Renew
    private void RenewPDF()
    {
        if (lblLastYearRefNo.Text.Trim() != "")
        {
            MyDatabase _db = new MyDatabase();
            StringBuilder _str = new StringBuilder();
            _str.Append("SELECT TOP 1 Name, CarPlate, CoverageStart FROM tblNonGGCarMoreDetails MD ");
            _str.Append("WHERE QuoteRefNo = '" + lblLastYearRefNo.Text + "' ");
            _str.Append("AND RefCEUserId = " + txtCustomerId.Text + " ORDER BY CreatedDate DESC");
            DataTable _dtSelect = new DataTable("dtSelect");
            _dtSelect = _db.GetDataTable(_str.ToString());
            if (_dtSelect != null && _dtSelect.Rows.Count > 0)
            {
                DataRow _dr = _dtSelect.Rows[0];
                string sharedlink = "http://zebra/cx/";
                string cName = _dr["Name"].ToString();
                string cPlate = _dr["CarPlate"].ToString();
                string cDate = Convert.ToDateTime(_dr["CoverageStart"]).ToString("dd/MM/yyyy");
                if (cDate.Trim() != "")
                {
                    string[] path = cDate.Split('/');
                    linkPdf.Text = "ดู Pdf";
                    if (cPlate.Trim() != "ป้ายแดง")
                    {
                        linkPdf.NavigateUrl = sharedlink + (int.Parse(path[2]) + 1) + "/" + path[1] + "/" + cPlate.Trim() + ".pdf";
                    }
                    else
                    {
                        cName = cName.Trim().Replace(" ", "%20");
                        linkPdf.NavigateUrl = sharedlink + (int.Parse(path[2]) + 1) + "/" + path[1] + "/" + cName.Trim() + ".pdf";
                    }
                }
            }
        }
    }
    #endregion

    #region CallHistory

    //public void GetCallHistory()
    //{
    //    if (txtCustomerId.Text != string.Empty && txtCustomerId.Text != "0")
    //    {
    //        DataTable _dtHistory = new DataTable();
    //        try
    //        {
    //            bool hasValue = false;
    //            MyDatabase _db = new MyDatabase("GG_CRMDBConnectionString");
    //            SortedList _sPara = new SortedList();
    //            string _spName = "sprocCXCRMGetCallStatusLogHistory";
    //            _sPara.Add("@CustomerID", Convert.ToInt64(txtCustomerId.Text.Trim()));
    //            _sPara.Add("@LangOption", Convert.ToInt64(lblLangOption.Text.Trim()));
    //            _dtHistory = _db.GetDataTableBySP(_spName, _sPara);
    //            if (_dtHistory != null)
    //            {
    //                if (_dtHistory.Rows.Count > 0)
    //                {
    //                    StringBuilder rBuilder = new StringBuilder();
    //                    StringBuilder cBuilder = new StringBuilder();
    //                    hasValue = true;

    //                    foreach (DataRow _dr in _dtHistory.Rows)
    //                    {
    //                        cBuilder.Remove(0, cBuilder.Length);

    //                        cBuilder.Append(ScriptUtil.GenerateLineColumn(_dr.IsNull("FULLNAME") ? String.Empty : _dr["FULLNAME"].ToString()));
    //                        if (_dr["CarID"].ToString() == txtCarId.Text)
    //                        {
    //                            cBuilder.Append(ScriptUtil.GenerateColorMColumn(_dr["CarID"].ToString()));
    //                            cBuilder.Append(ScriptUtil.GenerateColorColumn(_dr["CallTypeDesc"].ToString()));

    //                            lblCallHistoryFoundCount.Text = (Convert.ToInt32(lblCallHistoryFoundCount.Text) + 1).ToString();
    //                            lblCallHistoryMessage.Text = "(" + lblCallHistoryFoundCount.Text + ") " + Resources.General.Callhistoryfound + "";
    //                            lblCallHistoryFoundCount.Visible = false;
    //                        }
    //                        else
    //                        {
    //                            cBuilder.Append(ScriptUtil.GenerateLineColumn(_dr["CarID"].ToString()));
    //                            cBuilder.Append(ScriptUtil.GenerateLineColumn(_dr["CallTypeDesc"].ToString()));

    //                            if (lblCallHistoryFoundCount.Text == "0")
    //                                lblCallHistoryMessage.Text = Resources.General.Nocallhistoryfor + " " + Resources.CarInsurance.CarId + ": " + txtCarId.Text;
    //                        }
    //                        cBuilder.Append(ScriptUtil.GenerateLineColumn(_dr.IsNull("CallFinish") ? String.Empty : _dr["CallFinish"].ToString()));
    //                        cBuilder.Append(ScriptUtil.GenerateLineColumn(_dr.IsNull("CallStatusDesc") ? String.Empty : _dr["CallStatusDesc"].ToString()));
    //                        cBuilder.Append(ScriptUtil.GenerateLineColumn(_dr.IsNull("CallDurationDesc") ? String.Empty : _dr["CallDurationDesc"].ToString()));
    //                        cBuilder.Append(ScriptUtil.GenerateLineColumn(_dr.IsNull("Remark") ? String.Empty : _dr["Remark"].ToString()));
    //                        cBuilder.Append(ScriptUtil.GenerateLineColumn(_dr.IsNull("ModifiedDate") ? String.Empty : Convert.ToDateTime(_dr["ModifiedDate"]).ToString("dd-MMM-yyyy hh:mm tt")));

    //                        rBuilder.Append(ScriptUtil.GenerateRowYellow(cBuilder.ToString()));
    //                    }
    //                    this.ltrCallHistory.Text = rBuilder.ToString();
    //                }
    //            }

    //            if (!hasValue)
    //            {
    //                lblCallHistoryMessage.Text = Resources.General.Nocallhistoryfor + " " + Resources.CarInsurance.CarId + ": " + txtCarId.Text;
    //                lblCallHistoryFoundCount.Visible = false;
    //            }
    //        }
    //        finally
    //        {
    //            _dtHistory.Dispose();
    //        }
    //    }
    //}

    #endregion

    #region Kawna

    //<asp:DropDownList ID="ddlNCarYear" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlNCarYear_SelectedIndexChanged"></asp:DropDownList>
    //<asp:RequiredFieldValidator runat="server" ID="rfvNCarYear" ControlToValidate="ddlNCarYear"
    //    ErrorMessage="" Text="*" InitialValue="-1" ValidationGroup="newsearch" Display="Dynamic"></asp:RequiredFieldValidator>
    //<asp:DropDownList runat="server" ID="ddlNCarMake" Width="100px" AutoPostBack="true"
    //    OnSelectedIndexChanged="ddlNCarMake_SelectedIndexChanged">
    //    <asp:ListItem Value="-1" Text="<%$ Resources:General,Select%>"></asp:ListItem>
    //</asp:DropDownList>
    //<asp:RequiredFieldValidator runat="server" ID="rfvNCarMake" ControlToValidate="ddlNCarMake"
    //    ErrorMessage="" Text="*" InitialValue="-1" ValidationGroup="newsearch" Display="Dynamic"></asp:RequiredFieldValidator>
    //<asp:DropDownList runat="server" ID="ddlNModelBodyCCDoor">
    //    <asp:ListItem Value="-1" Text="<%$ Resources:General,Select%>"></asp:ListItem>
    //</asp:DropDownList>
    //<asp:RequiredFieldValidator runat="server" ID="rfvNModelBodyCCDoor" ControlToValidate="ddlNModelBodyCCDoor"
    //    ErrorMessage="" Text="*" InitialValue="-1" ValidationGroup="newsearch" Display="Dynamic"></asp:RequiredFieldValidator>

    private void SetKawna(DataRow drCarPolicy, DataRow drCarDetail)
    {
        LoadNClass();
        if (lblInsuranceType.Text == "1")
        {
            ddlNInsuranceType.SelectedIndex = ddlNInsuranceType.Items.IndexOf(ddlNInsuranceType.Items.FindByValue("10"));
        }
        else if (lblInsuranceType.Text == "1+")
        {
            ddlNInsuranceType.SelectedIndex = ddlNInsuranceType.Items.IndexOf(ddlNInsuranceType.Items.FindByValue("11"));
        }
        else if (lblInsuranceType.Text == "2")
        {
            ddlNInsuranceType.SelectedIndex = ddlNInsuranceType.Items.IndexOf(ddlNInsuranceType.Items.FindByValue("20"));
        }
        else if (lblInsuranceType.Text == "2+")
        {
            ddlNInsuranceType.SelectedIndex = ddlNInsuranceType.Items.IndexOf(ddlNInsuranceType.Items.FindByValue("21"));
        }
        else if (lblInsuranceType.Text == "3")
        {
            ddlNInsuranceType.SelectedIndex = ddlNInsuranceType.Items.IndexOf(ddlNInsuranceType.Items.FindByValue("30"));
        }
        else if (lblInsuranceType.Text == "3+")
        {
            ddlNInsuranceType.SelectedIndex = ddlNInsuranceType.Items.IndexOf(ddlNInsuranceType.Items.FindByValue("31"));
        }

        //Yui@5/2/2014
        if (ddlNInsuranceType.SelectedIndex == 0)
            ddlNInsuranceType.SelectedIndex = 1;
        //ddlNNCB.Enabled = true;
        //rfvNNCB.Enabled = true;
        //ddlNAnyClaim.Enabled = true;
        //rfvNAnyClaim.Enabled = true;
        //LoadNCurrentInsurer();
        //ddlNCurrentProvider.Enabled = true;
        //ddlNNamedDrivers.Enabled = true;
        //ddlNProvinceRegistration.Enabled = true;
        //rfvNProvinceRegistration.Enabled = true;
        //************
        
        
        //LoadNCarYear();
        LoadNInsurer();
        MyDatabase _db = new MyDatabase();
        DataTable _dtSearch = new DataTable("tblSearch");
        SortedList paraList = new SortedList();
        paraList.Add("@CarId", txtCarId.Text);
        _dtSearch = _db.GetDataTableBySP("sprocKawnaGetSearchCar", paraList);
        if (_dtSearch != null && _dtSearch.Rows.Count > 0)
        {
            DataRow drSearch = _dtSearch.Rows[0];

            ddlNInsuranceType.SelectedIndex = ddlNInsuranceType.Items.IndexOf(ddlNInsuranceType.Items.FindByValue(drSearch["InsuranceType"].ToString()));

            //Yui@24/2/2014
            //ddlNCarYear.SelectedIndex = ddlNCarYear.Items.IndexOf(ddlNCarYear.Items.FindByValue(drSearch["CarYear"].ToString()));
            //GetNCarMakeList(ddlNCarMake);
            //ddlNCarMake.SelectedIndex = ddlNCarMake.Items.IndexOf(ddlNCarMake.Items.FindByValue(drSearch["CarMake"].ToString()));
            //ddlNCarMake_SelectedIndexChanged(null, null);
            //string _tempDesc = drSearch["CarModel"].ToString() + " " + drSearch["Body"].ToString() + " " + drSearch["CC"].ToString() + "cc " + drSearch["Door"].ToString() + " doors";
            //ddlNModelBodyCCDoor.Text = _tempDesc;
            //*************

            //Yui@5/2/2014
            //ddlNNCB.SelectedIndex = ddlNNCB.Items.IndexOf(ddlNNCB.Items.FindByValue(drSearch["NCB"].ToString()));
            //ddlNAnyClaim.SelectedIndex = ddlNAnyClaim.Items.IndexOf(ddlNAnyClaim.Items.FindByValue(drSearch["Claim"].ToString()));
            //ddlNProvinceRegistration.SelectedIndex = ddlNProvinceRegistration.Items.IndexOf(ddlNProvinceRegistration.Items.FindByValue(drSearch["ProvinceRegistration"].ToString()));
            //if (drSearch["IsCTPL"].ToString().ToLower() == "true")
            //{
            //    ddlNCTPL.SelectedIndex = ddlNCTPL.Items.IndexOf(ddlNCTPL.Items.FindByValue("1"));
            //}
            //else
            //{
            //    ddlNCTPL.SelectedIndex = ddlNCTPL.Items.IndexOf(ddlNCTPL.Items.FindByValue("0"));
            //}
            //txtNAccModAmount.Text = drSearch["AddAccModAmount"].ToString();
            //if (txtNAccModAmount.Text.Trim() == "") txtNAccModAmount.Text = "0";
            ddlNFlood.SelectedIndex = ddlNFlood.Items.IndexOf(ddlNFlood.Items.FindByValue(drSearch["CoverFlood"].ToString()));
            ddlNSeat.SelectedIndex = ddlNSeat.Items.IndexOf(ddlNSeat.Items.FindByValue(drSearch["NumSeat"].ToString()));
            ddlNVehicleType.SelectedIndex = ddlNVehicleType.Items.IndexOf(ddlNVehicleType.Items.FindByValue(drSearch["VehicleCode"].ToString()));
            lblNLastUpdate.Text = "Last updated " + Convert.ToDateTime(drSearch["ModifiedDate"]).ToString("dd/MMM/yyyy");
            ddlNInsuranceCompany.SelectedIndex = ddlNInsuranceCompany.Items.IndexOf(ddlNInsuranceCompany.Items.FindByValue(drSearch["ProviderCompanyId"].ToString()));
            //************

            ddlQueryGarageType.SelectedIndex = ddlQueryGarageType.Items.IndexOf(ddlQueryGarageType.Items.FindByValue(drSearch["GarageType"].ToString()));
            ddlNDeduct.SelectedIndex = ddlNDeduct.Items.IndexOf(ddlNDeduct.Items.FindByValue(drSearch["Deductible"].ToString()));

            //Yui@24/2/2014
            ddlNCarType.SelectedIndex = ddlNCarType.Items.IndexOf(ddlNCarType.Items.FindByValue(drSearch["VehicleCode"].ToString()));
            chkIsEurope.Checked = false;
            if (drSearch["IsEuropeCar"] != DBNull.Value)
                if (drSearch["IsEuropeCar"].ToString().ToLower() == "true")
                    chkIsEurope.Checked = true;

            ddlNCarYear.SelectedIndex = ddlNCarYear.Items.IndexOf(ddlNCarYear.Items.FindByValue(drSearch["CarYear"].ToString()));
            ddlNCarModel.SelectedIndex = ddlNCarModel.Items.IndexOf(ddlNCarModel.Items.FindByValue(drSearch["CarModel"].ToString()));
            ddlNIsClaim.SelectedIndex = ddlNIsClaim.Items.IndexOf(ddlNIsClaim.Items.FindByValue(drSearch["Claim"].ToString()));
            ddlNDriverAge.SelectedIndex = ddlNDriverAge.Items.IndexOf(ddlNDriverAge.Items.FindByValue(drSearch["Driver1"].ToString()));
            ddlNRegistraProvince.SelectedIndex = ddlNRegistraProvince.Items.IndexOf(ddlNRegistraProvince.Items.FindByValue(drSearch["ProvinceRegistration"].ToString()));
            if (ddlNInsuranceType.SelectedValue == "10" || ddlNInsuranceType.SelectedValue == "11")
            {
                trClass11.Style.Remove("display");
                trClass12.Style.Remove("display");
            }
            else
            {
                trClass11.Style.Add("display", "none");
                trClass12.Style.Add("display", "none");
            }

            GetSumInsure();
            ddlNSumInsured.SelectedIndex = ddlNSumInsured.Items.IndexOf(ddlNSumInsured.Items.FindByValue(drSearch["SumInsured"].ToString()));

            //Yui@5/2/2014
            //ddlNCurrentProvider.SelectedIndex = ddlNCurrentProvider.Items.IndexOf(ddlNCurrentProvider.Items.FindByValue(drSearch["OldInsurer"].ToString()));
            //string IsAddDriver = "0";
            //if (drSearch["IsAddDriver"].ToString().ToLower() == "true")
            //{
            //    IsAddDriver = "1";
            //}
            //ddlNNamedDrivers.SelectedIndex = ddlNNamedDrivers.Items.IndexOf(ddlNNamedDrivers.Items.FindByValue(IsAddDriver));
            //GetTempResultExcelOne();
            //************
        }
        else
        {
            GetSumInsure();

            //Yui@5/2/2014
            //ddlNNamedDrivers.SelectedIndex = ddlNNamedDrivers.Items.IndexOf(ddlNNamedDrivers.Items.FindByValue("0"));
            //************

            //Yui@24/2/2014
            //if (drCarDetail != null) ddlNCarYear.SelectedIndex = ddlNCarYear.Items.IndexOf(ddlNCarYear.Items.FindByValue(drCarDetail["ManufactYear"].ToString()));
            //GetNCarMakeList(ddlNCarMake);
            //*************
            if (drCarDetail != null)
            {
                //Yui@24/2/2014
                //ddlNCarMake.SelectedIndex = ddlNCarMake.Items.IndexOf(ddlNCarMake.Items.FindByValue(drCarDetail["CarMake"].ToString()));
                //ddlNCarMake_SelectedIndexChanged(null, null);
                //string _tempDesc = drCarDetail["CarModel"].ToString() + " " + drCarDetail["Body"].ToString() + " " + drCarDetail["CC"].ToString() + "cc " + drCarDetail["Door"].ToString() + " doors";
                //ddlNModelBodyCCDoor.Text = _tempDesc;
                //*************

                //Yui@5/2/2014
                //ddlNNCB.SelectedIndex = ddlNNCB.Items.IndexOf(ddlNNCB.Items.FindByValue(drCarPolicy["NCDPercent"].ToString()));
                //ddlNAnyClaim.SelectedIndex = ddlNAnyClaim.Items.IndexOf(ddlNAnyClaim.Items.FindByValue(drCarPolicy["IsClaimLastYear"].ToString()));
                //ddlNCurrentProvider.SelectedIndex = ddlNCurrentProvider.Items.IndexOf(ddlNCurrentProvider.Items.FindByValue(drCarPolicy["Info1"].ToString()));
                //ddlNProvinceRegistration.SelectedIndex = ddlNProvinceRegistration.Items.IndexOf(
                //ddlNProvinceRegistration.Items.FindByValue(drCarPolicy["ProvinceRegistration"].ToString()));
                //if (drCarPolicy["IsCTPL"].ToString().ToLower() == "true")
                //{
                //    ddlNCTPL.SelectedIndex = ddlNCTPL.Items.IndexOf(ddlNCTPL.Items.FindByValue("1"));
                //}
                //else
                //{
                //    ddlNCTPL.SelectedIndex = ddlNCTPL.Items.IndexOf(ddlNCTPL.Items.FindByValue("0"));
                //}
                //ddlNCTPL.SelectedIndex = ddlNCTPL.Items.IndexOf(ddlNCTPL.Items.FindByValue(drCarPolicy["IsCTPL"].ToString()));
                //************

                ddlNDeduct.SelectedIndex = ddlNDeduct.Items.IndexOf(ddlNDeduct.Items.FindByValue(drCarPolicy["Deductible"].ToString()));
                
                //Yui@5/2/2014
                //if (drCarPolicy["IsClaimLastYear"].ToString().ToLower() == "true")
                //{
                //    ddlNAnyClaim.SelectedIndex = ddlNAnyClaim.Items.IndexOf(ddlNAnyClaim.Items.FindByValue("1"));
                //}
                //else
                //{
                //    ddlNAnyClaim.SelectedIndex = ddlNAnyClaim.Items.IndexOf(ddlNAnyClaim.Items.FindByValue("0"));
                //}
                //txtNAccModAmount.Text = drCarPolicy["AddAccModAmount"].ToString();
                //if (txtNAccModAmount.Text.Trim() == "") txtNAccModAmount.Text = "0";
                //if (Convert.ToInt16(drCarPolicy["NoOfDriver"].ToString()) > 0)
                //{
                //    ddlNNamedDrivers.SelectedIndex = ddlNNamedDrivers.Items.IndexOf(ddlNNamedDrivers.Items.FindByValue("1"));
                //}
                //************
            }
        }

        SortedList _paraList = new SortedList();
        _paraList.Add("@CECarID", txtCarId.Text);
        _paraList.Add("@ProductType", "CIN");
        _paraList.Add("@RefCEUserId", "0");
        _paraList.Add("@LangOption", "1");
        DataTable _dtPremiumList = new DataTable("tblPremiumList");
        _dtPremiumList = _db.GetDataTableBySP("sprocCXOnlinePremiumSelectItemListExcel", _paraList);
        //Update in datagrid
        grdExcelSelect.DataSource = _dtPremiumList;
        grdExcelSelect.DataBind();

        string _useKawna = ConfigurationManager.AppSettings["UseKawna"].ToString();
        if (_useKawna == "0")
        {
            btnNewSearch.Enabled = false;
        }
    }

    //public int CalculateAgeCorrect(DateTime birthDate, DateTime now)
    //{
    //    int age = now.Year - birthDate.Year;
    //    if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day)) age--;
    //    return age;
    //}

    //private void SetDriverAge(int age, DropDownList ddl)
    //{
    //    if (age >= 18 && age <= 24)
    //    {
    //        ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue("1"));
    //    }
    //    else if (age >= 25 && age <= 35)
    //    {
    //        ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue("2"));
    //    }
    //    else if (age >= 36 && age <= 50)
    //    {
    //        ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue("3"));
    //    }
    //    else if (age > 50)
    //    {
    //        ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue("4"));
    //    }
    //}

    //Yui@24/2/2014
    //private void LoadNCarYear()
    //{
    //    string selectYear = ddlNCarYear.Text;
    //    int _yearCount = 10;
    //    ddlNCarYear.Items.Clear();
    //    if (ddlNInsuranceType.Text != "-1")
    //    {
    //        if (Convert.ToInt32(ddlNInsuranceType.Text) >= 20)
    //        {
    //            _yearCount = 25;
    //        }
    //        int _startYear = DateTime.Now.AddYears(-1).Year - _yearCount;
    //        int _endYear = DateTime.Now.AddYears(-1).Year;
    //        for (int i = _endYear; i > _startYear; i--)
    //        {
    //            if (lblLangOption.Text.Trim() != "1")
    //            {
    //                ddlNCarYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
    //            }
    //            else
    //            {
    //                ddlNCarYear.Items.Add(new ListItem(i.ToString() + " - พ.ศ. " + (i + 543).ToString(), i.ToString()));
    //            }
    //        }
    //    }
    //    ddlNCarYear.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    //    if (selectYear != "-1") ddlNCarYear.SelectedIndex = ddlNCarYear.Items.IndexOf(ddlNCarYear.Items.FindByValue(selectYear));
    //}

    //Yui@5/2/2014
    //public void LoadNCurrentInsurer()
    //{
    //    DataTable dtPreInsurerComp = General.GetComboItem(Resources.DBTable.PreInsurer, Resources.DBTable.OrderByField, true);
    //    ddlNCurrentProvider.DataSource = dtPreInsurerComp;
    //    ddlNCurrentProvider.DataTextField = dtPreInsurerComp.Columns[0].ColumnName.ToString();
    //    ddlNCurrentProvider.DataValueField = dtPreInsurerComp.Columns[1].ColumnName.ToString();
    //    ddlNCurrentProvider.DataBind();
    //    ddlNCurrentProvider.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    //}

    public void LoadNInsurer()
    {
        DataTable dtPreInsurerComp = General.GetComboItem("BrokerProvider", true);
        ddlNInsuranceCompany.DataSource = dtPreInsurerComp;
        ddlNInsuranceCompany.DataTextField = dtPreInsurerComp.Columns[0].ColumnName.ToString();
        ddlNInsuranceCompany.DataValueField = dtPreInsurerComp.Columns[1].ColumnName.ToString();
        ddlNInsuranceCompany.DataBind();
        ddlNInsuranceCompany.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    }

    protected void ddlNInsuranceType_SelectedIndexChanged(object sender, EventArgs e)
    {
        GetSumInsure();
    }

    protected void ddlNCarYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        GetSumInsure();
    }

    protected void ddlNCarModel_SelectedIndexChanged(object sender, EventArgs e)
    {
        GetSumInsure();
    }

    private void GetSumInsure()
    {
        ddlNSumInsured.Items.Clear();
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable();
        StringBuilder _query = new StringBuilder();
        _query.Append("SELECT DISTINCT SumInsured FROM tblPremiumExcel WHERE TypeOfPlan='" + ddlNInsuranceType.SelectedValue + "' ");
        if (ddlNInsuranceType.SelectedValue == "10")
        {
            _query.Append("AND CarYear = '" + ddlNCarYear.SelectedValue + "' ");
        }
        _query.Append("ORDER BY SumInsured");
        _dt = _db.GetDataTable(_query.ToString());
        ddlNSumInsured.DataSource = _dt;
        ddlNSumInsured.DataTextField = "SumInsured";
        ddlNSumInsured.DataValueField = "SumInsured";
        ddlNSumInsured.DataBind();
        ddlNSumInsured.Items.Insert(0, new ListItem(Resources.General.Select, "-1"));
        //ddlNSumInsured.Items.Insert(1, new ListItem("100000-150000", "100000"));
        //ddlNSumInsured.Items.Insert(2, new ListItem("150001-200000", "150001"));
        //ddlNSumInsured.Items.Insert(3, new ListItem("200001-250000", "200001"));
        //ddlNSumInsured.Items.Insert(4, new ListItem("250001-300000", "250001"));
        //ddlNSumInsured.Items.Insert(5, new ListItem("300001-350000", "300001"));
        //ddlNSumInsured.Items.Insert(6, new ListItem("350001-400000", "350001"));
        //ddlNSumInsured.Items.Insert(7, new ListItem("400001-450000", "400001"));
        //ddlNSumInsured.Items.Insert(8, new ListItem("450001-500000", "450001"));
        //ddlNSumInsured.Items.Insert(9, new ListItem("500001-550000", "500001"));
        //ddlNSumInsured.Items.Insert(10, new ListItem("550001-600000", "550001"));
        //ddlNSumInsured.Items.Insert(11, new ListItem("600001-650000", "600001"));
        //ddlNSumInsured.Items.Insert(12, new ListItem("650001-700000", "650001"));
    }

    public void LoadNClass()
    {
        ddlNInsuranceType.Items.Clear();
        ddlNInsuranceType.Items.Add(new ListItem(Resources.General.Select, "-1"));
        ddlNInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassOne, "10"));
        //ddlNInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassOneLowCost, "11"));
        ddlNInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassTwoPlus, "21"));
        //ddlNInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassTwoPlus, "20"));
        ddlNInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassThreePlus, "31"));
        ddlNInsuranceType.Items.Add(new ListItem(Resources.CarInsurance.Insurance_ClassThree, "30"));
    }

    //Yui@24/2/2014
    //private void ClearNAllList()
    //{
    //    ddlNModelBodyCCDoor.Items.Clear();
    //    ddlNModelBodyCCDoor.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
    //}

    //private void GetNCarMakeList(DropDownList ddlList)
    //{
    //    MyDatabase _db = new MyDatabase();
    //    DataTable _dt = new DataTable("tblMake");
    //    //SortedList _spList = new SortedList();
    //    //_spList.Add("@Year", Year);
    //    _dt = _db.GetDataTableBySP("sprocKawnaGetCarMakeListByYear"); //, _spList
    //    ddlList.Items.Clear();
    //    if (_dt != null && _dt.Rows.Count > 0)
    //    {
    //        ddlList.DataSource = _dt;
    //        ddlList.DataTextField = "MakeDesc";
    //        ddlList.DataValueField = "MakeCode";
    //        ddlList.DataBind();
    //    }
    //    ddlList.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    //    _dt = null;
    //    _db = null;
    //}

    //private void GetNCarModelDescList(string CarMake, string Year, DropDownList ddlList)
    //{
    //    MyDatabase _db = new MyDatabase();
    //    DataTable _dt = new DataTable("tblModelDesc");
    //    SortedList _spList = new SortedList();
    //    _spList.Add("@CarMake", CarMake);
    //    _spList.Add("@Year", Year);
    //    _dt = _db.GetDataTableBySP("sprocKawnaGetCarModelDescListByCarMakeCode", _spList);
    //    ddlList.Items.Clear();
    //    if (_dt != null && _dt.Rows.Count > 0)
    //    {
    //        ddlList.DataSource = _dt;
    //        ddlList.DataTextField = "CarModelDisplay";
    //        ddlList.DataValueField = "CarModelDesc";
    //        ddlList.DataBind();
    //    }
    //    ddlList.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    //    _dt = null;
    //    _db = null;
    //}

    //Yui@24/2/2014
    //protected void ddlNCarYear_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    if (ddlNCarMake.Items.Count > 1)
    //    {
    //        ddlNCarMake_SelectedIndexChanged(sender, e);
    //    }
    //}

    //Yui@24/2/2014
    //protected void ddlNCarMake_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    if (ddlNCarMake.Text == "-1")
    //    {
    //        ddlNModelBodyCCDoor.Items.Clear();
    //        ddlNModelBodyCCDoor.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
    //    }
    //    else
    //    {
    //        GetNCarModelDescList(ddlNCarMake.Text, ddlNCarYear.Text, ddlNModelBodyCCDoor);
    //        if (ddlNModelBodyCCDoor.Items.Count > 0)
    //        {
    //            ddlNModelBodyCCDoor.SelectedIndex = 0;
    //        }
    //    }
    //}

    protected void btnNewSearch_Click(object sender, EventArgs e)
    {
        try
        {
            hidQuoteEmailId.Value = "";

            MyDatabase _db = new MyDatabase();
            // *** Search Packages ***
            string spName = "[sprocKawnaSearchInsertUpdateSingleItem]";
            SortedList paraList = new SortedList();

            paraList.Add("@CarId", txtCarId.Text);
            paraList.Add("@InsuranceType", ddlNInsuranceType.Text);

            //Yui@24/2/2014
            //paraList.Add("@CarYear", ddlNCarYear.Text);
            //paraList.Add("@CarMake", ddlNCarMake.SelectedItem.Value);
            //string[] _tempDesc = ddlNModelBodyCCDoor.SelectedItem.Text.Split(' ');
            //string _model = "";
            //string _body = "";
            //string _cc = "";
            //string _door = "";
            //if (_tempDesc.Length == 5)
            //{
            //    _model = _tempDesc[0];
            //    _body = _tempDesc[1];
            //    _cc = _tempDesc[2].Substring(0, _tempDesc[2].Length - 2);
            //    _door = _tempDesc[3];
            //}
            //else if (_tempDesc.Length == 6)
            //{
            //    _model = _tempDesc[0] + " " + _tempDesc[1];
            //    _body = _tempDesc[2];
            //    _cc = _tempDesc[3].Substring(0, _tempDesc[3].Length - 2);
            //    _door = _tempDesc[4];
            //}
            //else if (_tempDesc.Length == 7)
            //{
            //    _model = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
            //    _body = _tempDesc[3];
            //    _cc = _tempDesc[4].Substring(0, _tempDesc[4].Length - 2);
            //    _door = _tempDesc[5];
            //}

            //string CC = "";
            //string[] _tempCC = ddlNModelBodyCCDoor.SelectedItem.Value.Split(' ');
            //if (_tempCC.Length == 5)
            //{
            //    CC = _tempCC[2].Substring(0, _tempCC[2].Length - 2);
            //}
            //else if (_tempCC.Length == 6)
            //{
            //    CC = _tempCC[3].Substring(0, _tempCC[3].Length - 2);
            //}
            //else if (_tempCC.Length == 7)
            //{
            //    CC = _tempCC[4].Substring(0, _tempCC[4].Length - 2);
            //}
            //paraList.Add("@CarModel", _model);
            //paraList.Add("@Body", _body);
            //paraList.Add("@CC", CC);
            //paraList.Add("@CC_TH", _cc);
            //paraList.Add("@Door", _door);
            //paraList.Add("@RGB", "");
            //*******************************************

            paraList.Add("@Body", DBNull.Value);
            paraList.Add("@CC", DBNull.Value);
            paraList.Add("@CC_TH", DBNull.Value);
            paraList.Add("@Door", DBNull.Value);
            paraList.Add("@RGB", DBNull.Value);

            paraList.Add("@UseInProvinceId", DBNull.Value);
            paraList.Add("@RegisterInProvinceId", DBNull.Value);
            paraList.Add("@HasOldPolicy", DBNull.Value);
            paraList.Add("@OldInsuranceType", DBNull.Value);
            
            //Yui@5/2/2014
            //paraList.Add("@NCB", ddlNNCB.Text);
            //paraList.Add("@OldInsurer", ddlNCurrentProvider.Text);
            //paraList.Add("@Claim", ddlNAnyClaim.Text);
            //paraList.Add("@IsAddDriver", ddlNNamedDrivers.Text);
            //paraList.Add("@ProvinceRegistration", ddlNProvinceRegistration.SelectedValue);
            //paraList.Add("@IsCTPL", ddlNCTPL.Text);
            //paraList.Add("@AddAccModAmount", txtNAccModAmount.Text);
            //paraList.Add("@SumInsured", DBNull.Value);
            paraList.Add("@NCB", DBNull.Value);
            paraList.Add("@OldInsurer", DBNull.Value);
            paraList.Add("@IsAddDriver", DBNull.Value);
            paraList.Add("@IsCTPL", DBNull.Value);
            paraList.Add("@AddAccModAmount", DBNull.Value);
            if (ddlNSumInsured.SelectedIndex != 0)
                paraList.Add("@SumInsured", ddlNSumInsured.SelectedValue);
            else
                paraList.Add("@SumInsured", DBNull.Value);

            if (ddlNFlood.SelectedIndex != 0)
                paraList.Add("@CoverFlood", ddlNFlood.SelectedValue);
            else
                paraList.Add("@CoverFlood", DBNull.Value);

            if (ddlNSeat.SelectedIndex != 0)
                paraList.Add("@NumSeat", ddlNSeat.SelectedValue);
            else
                paraList.Add("@NumSeat", DBNull.Value);

            //if (ddlNVehicleType.SelectedIndex != 0)
            //    paraList.Add("@VehicleCode", ddlNVehicleType.SelectedValue);
            //else
            //    paraList.Add("@VehicleCode", DBNull.Value);

            if (ddlQueryGarageType.SelectedIndex != 0)
                paraList.Add("@GarageType", ddlQueryGarageType.Text);
            else
                paraList.Add("@GarageType", DBNull.Value);

            if (ddlNInsuranceCompany.SelectedIndex != 0)
                paraList.Add("@ProviderCompanyId", ddlNInsuranceCompany.SelectedValue);
            else
                paraList.Add("@ProviderCompanyId", DBNull.Value);
            //************
            
            paraList.Add("@IsNextYear", DBNull.Value);
            paraList.Add("@Deductible", ddlNDeduct.Text);
            paraList.Add("@Driver2", DBNull.Value);
            
            if (ddlNInsuranceType.SelectedValue == "10" || ddlNInsuranceType.SelectedValue == "11")
            {
                paraList.Add("@CarYear", ddlNCarYear.SelectedValue);
                paraList.Add("@CarMake", "TOYO");
                paraList.Add("@CarModel", ddlNCarModel.SelectedValue);

                if (ddlNIsClaim.SelectedIndex != 0)
                    paraList.Add("@Claim", ddlNIsClaim.SelectedValue);
                else
                    paraList.Add("@Claim", DBNull.Value);

                if (ddlNDriverAge.SelectedIndex != 0)
                    paraList.Add("@Driver1", ddlNDriverAge.SelectedValue);
                else
                    paraList.Add("@Driver1", DBNull.Value);

                if (ddlNRegistraProvince.SelectedIndex != 0)
                    paraList.Add("@ProvinceRegistration", ddlNRegistraProvince.SelectedValue);
                else
                    paraList.Add("@ProvinceRegistration", DBNull.Value);

                paraList.Add("@VehicleCode", "110");
                paraList.Add("@IsEuropeCar", DBNull.Value);
            }
            else
            {
                paraList.Add("@Claim", DBNull.Value);
                paraList.Add("@CarYear", DBNull.Value);
                paraList.Add("@CarMake", DBNull.Value);
                paraList.Add("@CarModel", DBNull.Value);
                paraList.Add("@Driver1", DBNull.Value);
                paraList.Add("@ProvinceRegistration", DBNull.Value);

                if (ddlNCarType.SelectedIndex != 0)
                    paraList.Add("@VehicleCode", ddlNCarType.SelectedValue);
                else
                    paraList.Add("@VehicleCode", DBNull.Value);
                paraList.Add("@IsEuropeCar", chkIsEurope.Checked);
            }
            
            _db.ExecuteScalarSP(spName, paraList);

            //sprocKawnaGetCarModelID
            //tblKawnaProvider
            
            try
            {
                //Yui@5/2/2014
                //string _spName = "";
                //SortedList _sPara = new SortedList();
                //_spName = "[sprocProviderCarInsuranceClearExcel]";
                //_sPara.Add("@CarId", txtCarId.Text);
                //_db.ExecuteNonSqlSP(_spName, _sPara);

                //Web Service BKI
                //BKIDetailDB bki = new BKIDetailDB();
                //bki.BKICalculation(Int64.Parse(txtCarId.Text), Int64.Parse(txtCustomerId.Text));
                
                //Get
                //_spName = "[sprocProviderCarInsuranceCalculationCRM]";
                //_sPara = new SortedList();
                //_sPara.Add("@CarId", txtCarId.Text);
                //_sPara.Add("@RefUserId", txtCustomerId.Text);
                //_db.ExecuteNonSqlSP(_spName, _sPara);

                //GetTempResultExcelOne();
                //************

                //Yui@5/2/2015
                //sprocCarInsurancePremiumSelectItemListExcel
                GetTempResultExcelOne();
                //Yui@24/2/2014
                //UpdateCar(Convert.ToInt32(txtCustomerId.Text));
            }
            catch (Exception ex)
            {
                lblMessageKawna.Text = ex.Message;
                gvCarResultExcel.DataSource = null;
                gvCarResultExcel.DataBind();
            }
        }
        catch (Exception)
        {
        }
    }

    //Yui@5/2/2015
    //OnClick="btnUpDateCar_Click"
    //Not Use
    #region UpdateCar

    //protected void btnUpDateCar_Click(object sender, EventArgs e)
    //{
    //    Int64 _userId = 0;

    //    if (!Int64.TryParse(txtCustomerId.Text, out _userId))
    //    {
    //        _userId = 0;
    //    }

    //    if (_userId == 0)
    //    {
    //        CarUserAccount _userAccount = GetCustomerAccount();

    //        if (_userAccount != null && _userAccount.CEID > 0)
    //        {
    //            txtCustomerId.Text = _userAccount.CEID.ToString();

    //            _userId = _userAccount.CEID;
    //        }
    //    }

    //    if (_userId > 0)
    //    {
    //        if (UpdateCar(_userId))
    //        {
    //            lblMessageKawna.Text = "Saved successfully!";
    //        }
    //        else
    //        {
    //            lblMessageKawna.Text = "Saving did NOT succeed!";
    //        }
    //    }
    //    else
    //    {
    //        lblMessageKawna.Text = "Please fill all require fields completly and correctly.";
    //    }
    //}

    //private CarUserAccount GetCustomerAccount()
    //{
    //    CarUserAccount _caruseraccount = new CarUserAccount();
    //    CarUserAccountDB _caruseraccountdb = new CarUserAccountDB();
    //    _caruseraccount = _caruseraccountdb.GetUserAccount(lblEmailAddress.Text.Trim(), Convert.ToInt32(CE.Global.CEUserType.Customer));



    //    return _caruseraccount;

    //}

    //private bool UpdateCar(Int64 UserID)
    //{
    //    Int64 _carresult = 0;
    //    Int64 _policyresult = 0;

    //    CarDetailTH _car = new CarDetailTH();
    //    CarDetailTHDB _cardb = new CarDetailTHDB();

    //    if (txtCarId.Text != string.Empty && txtCarId.Text != "0")
    //    {
    //        _car = _cardb.GetCar(Convert.ToInt64(txtCarId.Text.Trim()), 0);
    //        if (lblRenewalStaus.Text == "1" || lblRenewalStaus.Text == "2")
    //        {
    //            _car.Info4 = "RENEWAL-UPDATE" + lblRenewalStaus.Text;
    //        }
    //        else
    //        {
    //            _car.Info4 = "UPDATE";
    //        }
    //    }
    //    else
    //    {
    //        if (lblRenewalStaus.Text == "1" || lblRenewalStaus.Text == "2")
    //        {
    //            _car.Info4 = "RENEWAL-NEW" + lblRenewalStaus.Text;
    //        }
    //        else
    //        {
    //            _car.Info4 = "NEW";
    //        }
    //    }

    //    if (_car == null)
    //    {
    //        _car = new CarDetailTH();
    //        if (lblRenewalStaus.Text == "1" || lblRenewalStaus.Text == "2")
    //        {
    //            _car.Info4 = "RENEWAL-NEW" + lblRenewalStaus.Text;
    //        }
    //        else
    //        {
    //            _car.Info4 = "NEW";
    //        }
    //    }

    //    _car.ManufactYear = Convert.ToInt32(ddlNCarYear.SelectedValue.ToString());

    //    if (Session[General.UserId] != "0")
    //    {
    //        _car.Info2 = Session[General.UserId].ToString();
    //        _car.Info3 = dateTimeNow.ToString();
    //    }

    //    _car.CarMakeName = ddlNCarMake.Text;//Convert.ToInt32(txtCarMakeId.Text);
    //    _car.MakeModelDesc = ddlNCarMake.SelectedItem.Text + " " + ddlNModelBodyCCDoor.SelectedItem.Text;

    //    string[] _tempDesc = ddlNModelBodyCCDoor.Text.Split(' ');
    //    if (_tempDesc.Length == 5)
    //    {
    //        _car.CarModelName = _tempDesc[0];
    //        _car.Body = _tempDesc[1];
    //        _car.CC = Convert.ToInt32(_tempDesc[2].Substring(0, _tempDesc[2].Length - 2));
    //        _car.Door = Convert.ToInt32(_tempDesc[3]);
    //    }
    //    else if (_tempDesc.Length == 6)
    //    {
    //        _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1];
    //        _car.Body = _tempDesc[2];
    //        _car.CC = Convert.ToInt32(_tempDesc[3].Substring(0, _tempDesc[3].Length - 2));
    //        _car.Door = Convert.ToInt32(_tempDesc[4]);
    //    }
    //    else if (_tempDesc.Length == 7)
    //    {
    //        _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
    //        _car.Body = _tempDesc[3];
    //        _car.CC = Convert.ToInt32(_tempDesc[4].Substring(0, _tempDesc[4].Length - 2));
    //        _car.Door = Convert.ToInt32(_tempDesc[5]);
    //    }
    //    _car.GroupNo = 0; //Convert.ToInt32(txtGroupNo.Text);

    //    if (_car.Body == "PICKUP" && _car.Door == 2)
    //    {
    //        _car.Info2 = "PU";
    //        _car.Info3 = "320";
    //    }
    //    else
    //    {
    //        _car.Info2 = "PS";
    //        _car.Info3 = "210";
    //    }

    //    _car.Status = true;
    //    _car.RefCEUserId = UserID;
    //    _car.ViewedDetailId = 0;// Convert.ToInt64(Session[General.ViewedDetailsId].ToString());
    //    _car.CurrentStep = 1;
    //    _car.TotalStep = 4;
    //    if (ddlNCurrentProvider.Text != "-1")
    //        _car.Info1 = ddlNCurrentProvider.Text; //Current Insurer ID

    //    _carresult = _cardb.Insert(_car);

    //    _car = null;
    //    _cardb = null;


    //    if (_carresult > 0)
    //    {
    //        txtCarId.Text = _carresult.ToString();
    //        string CarPolicyId = txtCarPolicyId.Text;

    //        //CAR POLICY DETAILS
    //        if (CarPolicyId != string.Empty && CarPolicyId != "0")
    //        {
    //            CarPolicy _carpolicy = new CarPolicy();
    //            CarPolicyDB _carpolicydb = new CarPolicyDB();
    //            Int64 _carId = Convert.ToInt64(txtCarId.Text);
    //            Int64 _carpolicyid = 0;
    //            _carpolicyid = Convert.ToInt64(CarPolicyId);
    //            _carpolicy = _carpolicydb.GetCarPolicy(_carId, _carpolicyid, Convert.ToInt64(txtCustomerId.Text));

    //            _carpolicy.CECarPolicyId = _carpolicyid;
    //            //if (Session[General.AgentId] != null)
    //            //{
    //            _carpolicy.Info5 = "UPDATE";
    //            //}

    //            _carpolicy.Info8 = lblTESCO200.Text;

    //            lblMessageKawna.Text = "";
    //            if (Session[General.UserId] != null)
    //            {
    //                _carpolicy.Info2 = Session[General.UserId].ToString();
    //                _carpolicy.Info3 = dateTimeNow.ToString();
    //            }

    //            _carpolicy.CECarId = _carId;
    //            _carpolicy.InsuranceType = Convert.ToInt32(ddlNInsuranceType.Text);
    //            if (ddlQueryGarageType.SelectedValue != "-1") _carpolicy.GarageType = Convert.ToInt32(ddlQueryGarageType.Text);

    //            //Yui@06062014
    //            //string SumInsured = GetSumInsured();
    //            //if (SumInsured == "") SumInsured = "0";
    //            _carpolicy.SumInsured = 0; //Convert.ToInt32(SumInsured);

    //            _carpolicy.ProvinceRegistration = ddlNProvinceRegistration.SelectedValue;
    //            if (ddlNCTPL.Text == "1")
    //            {
    //                _carpolicy.IsCTPL = true;
    //            }
    //            else
    //            {
    //                _carpolicy.IsCTPL = false;
    //            }
    //            _carpolicy.Deductible = int.Parse(ddlNDeduct.Text);

    //            int accModAmt = 0;
    //            if (int.TryParse(txtNAccModAmount.Text, out accModAmt))
    //            {
    //                _carpolicy.AddAccModAmount = accModAmt;
    //                if (accModAmt > 0)
    //                {
    //                    _carpolicy.IsAddAccMod = true;
    //                }
    //                else
    //                {
    //                    _carpolicy.IsAddAccMod = false;
    //                }
    //            }
         
    //            _carpolicy.UseOfVehicle = "N/A";//ddlUseOfVehicle.Text;

    //            _carpolicy.NCDPercent = Convert.ToInt32(ddlNNCB.Text);
    //            ddlEditNCB.SelectedIndex = ddlEditNCB.Items.IndexOf(ddlEditNCB.Items.FindByValue(_carpolicy.NCDPercent.ToString()));

    //            if (ddlNAnyClaim.Text == "1")
    //            {
    //                _carpolicy.IsClaimLastYear = false;
    //            }
    //            else
    //            {
    //                _carpolicy.IsClaimLastYear = true;
    //            }

    //            if (ddlNNamedDrivers.Text != "0")
    //            {
    //                _carpolicy.IsAddDriver = true;
    //                _carpolicy.NoOfDriver = int.Parse(ddlNNamedDrivers.Text);
    //            }
    //            else
    //            {
    //                _carpolicy.IsAddDriver = false;
    //                _carpolicy.NoOfDriver = 0;
    //            }
    //            ddlEditNamedDriver.SelectedIndex = ddlEditNamedDriver.Items.IndexOf(ddlEditNamedDriver.Items.FindByValue(_carpolicy.NoOfDriver.ToString()));

    //            if (ddlNCurrentProvider.SelectedValue != "-1")
    //            {
    //                _carpolicy.CurrentInsurer = ddlNCurrentProvider.SelectedItem.Text;
    //            }

    //            _carpolicy.RefCEUserId = UserID;

    //            _carpolicy.Status = true;
    //            _carpolicy.CurrentStep = 2;

    //            //This is for GG Web
    //            _carpolicy.NInfo5 = 1;
    //            _carpolicy.Product = ddlNModelBodyCCDoor.Text;

    //            _policyresult = _carpolicydb.Insert(_carpolicy);

    //            _carpolicy = null;
    //            _carpolicydb = null;

    //            if (_policyresult > 0)
    //            {
    //                lblMessageKawna.Text += "<br>Car policy saved successfully!";
    //                lblMessageKawna.ForeColor = System.Drawing.Color.Blue;
    //            }
    //            else
    //            {
    //                lblMessageKawna.Text = "Car policy did not save successfully!";
    //                lblMessageKawna.ForeColor = System.Drawing.Color.Red;
    //                return false;
    //            }
    //        }

    //    }

    //    return _policyresult > 0;
    //}

    //Yui@24/2/2014
    //private bool UpdateCar(Int64 UserID)
    //{
    //    Int64 _carresult = 0;
    //    CarDetailTH _car = new CarDetailTH();
    //    CarDetailTHDB _cardb = new CarDetailTHDB();
    //    if (txtCarId.Text != string.Empty && txtCarId.Text != "0")
    //    {
    //        _car = _cardb.GetCar(Convert.ToInt64(txtCarId.Text.Trim()), 0);
    //        if (lblRenewalStaus.Text == "1" || lblRenewalStaus.Text == "2")
    //        {
    //            _car.Info4 = "RENEWAL-UPDATE" + lblRenewalStaus.Text;
    //        }
    //        else
    //        {
    //            _car.Info4 = "UPDATE";
    //        }
    //    }
    //    else
    //    {
    //        if (lblRenewalStaus.Text == "1" || lblRenewalStaus.Text == "2")
    //        {
    //            _car.Info4 = "RENEWAL-NEW" + lblRenewalStaus.Text;
    //        }
    //        else
    //        {
    //            _car.Info4 = "NEW";
    //        }
    //    }
    //    if (_car == null)
    //    {
    //        _car = new CarDetailTH();
    //        if (lblRenewalStaus.Text == "1" || lblRenewalStaus.Text == "2")
    //        {
    //            _car.Info4 = "RENEWAL-NEW" + lblRenewalStaus.Text;
    //        }
    //        else
    //        {
    //            _car.Info4 = "NEW";
    //        }
    //    }
    //    else
    //    {
    //        if (_car.ManufactYear == Convert.ToInt32(ddlNCarYear.SelectedValue.ToString()) &&
    //            _car.CarMakeName == ddlNCarMake.Text &&
    //            _car.MakeModelDesc == ddlNCarMake.SelectedItem.Text + " " + ddlNModelBodyCCDoor.SelectedItem.Text)
    //        {
    //            return true;
    //        }
    //    }
    //    _car.ManufactYear = Convert.ToInt32(ddlNCarYear.SelectedValue.ToString());
    //    // Update at the header
    //    lblRegYear.Text = ddlNCarYear.SelectedValue.ToString();
    //    if (Session[General.UserId] != "0")
    //    {
    //        _car.Info2 = Session[General.UserId].ToString();
    //        _car.Info3 = dateTimeNow.ToString();
    //    }
    //    _car.CarMakeName = ddlNCarMake.Text;//Convert.ToInt32(txtCarMakeId.Text);
    //    _car.MakeModelDesc = ddlNCarMake.SelectedItem.Text + " " + ddlNModelBodyCCDoor.SelectedItem.Text;
    //    // Update at the header
    //    lblCarMakeModel.Text = ddlNCarMake.SelectedItem.Text + " " + ddlNModelBodyCCDoor.SelectedItem.Text;
    //    string[] _tempDesc = ddlNModelBodyCCDoor.Text.Split(' ');
    //    if (_tempDesc.Length == 5)
    //    {
    //        _car.CarModelName = _tempDesc[0];
    //        _car.Body = _tempDesc[1];
    //        _car.CC = Convert.ToInt32(_tempDesc[2].Substring(0, _tempDesc[2].Length - 2));
    //        _car.Door = Convert.ToInt32(_tempDesc[3]);
    //    }
    //    else if (_tempDesc.Length == 6)
    //    {
    //        _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1];
    //        _car.Body = _tempDesc[2];
    //        _car.CC = Convert.ToInt32(_tempDesc[3].Substring(0, _tempDesc[3].Length - 2));
    //        _car.Door = Convert.ToInt32(_tempDesc[4]);
    //    }
    //    else if (_tempDesc.Length == 7)
    //    {
    //        _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
    //        _car.Body = _tempDesc[3];
    //        _car.CC = Convert.ToInt32(_tempDesc[4].Substring(0, _tempDesc[4].Length - 2));
    //        _car.Door = Convert.ToInt32(_tempDesc[5]);
    //    }
    //    _car.GroupNo = 0; //Convert.ToInt32(txtGroupNo.Text);
    //    if (_car.Body == "PICKUP" && _car.Door == 2)
    //    {
    //        _car.Info2 = "PU";
    //        _car.Info3 = "320";
    //    }
    //    else
    //    {
    //        _car.Info2 = "PS";
    //        _car.Info3 = "210";
    //    }
    //    _car.Status = true;
    //    _car.RefCEUserId = UserID;
    //    _car.ViewedDetailId = 0;// Convert.ToInt64(Session[General.ViewedDetailsId].ToString());
    //    _car.CurrentStep = 1;
    //    _car.TotalStep = 4;
    //    if (ddlNCurrentProvider.Text != "-1")
    //        _car.Info1 = ddlNCurrentProvider.Text; //Current Insurer ID
    //    _carresult = _cardb.Insert(_car);
    //    _car = null;
    //    _cardb = null;
    //    if (_carresult > 0)
    //        return true;
    //    else
    //        return false;
    //}

    #endregion

    #region Kawna Not Use

    //public Int64 DeleteCISelectedItem(Int64 CarId)
    //{
    //    MyDatabase _db = new MyDatabase();
    //    Int64 _result = -1;
    //    string _spName = "sprocCXCRMDeleteCarInsuranceSelectedItemByCarId";
    //    SortedList _sPara = new SortedList();
    //    #region Parameter
    //    _sPara.Add("@CarId", CarId);
    //    #endregion
    //    _result = _db.ExecuteSP(_spName, _sPara);
    //    return _result;
    //}

    //public DataSet GetCarDetails(Int64 CarId)
    //{
    //    MyDatabase _db = new MyDatabase();
    //    string _spName = "sprocCXCRMCarDetailsSingleItemByCarId";
    //    SortedList _spara = new SortedList();
    //    _spara.Add("@CarId", CarId);
    //    DataSet _ds = _db.GetDataSet(_spName, _spara);
    //    return _ds;
    //}

    //public void LoadDriverAge(DropDownList ddl)
    //{
    //    ddl.Items.Clear();
    //    ddl.Items.Add(new ListItem(Resources.General.Select, "-1"));
    //    ddl.Items.Add(new ListItem("18-24(5%)", "18"));
    //    ddl.Items.Add(new ListItem("25-35(10%)", "25"));
    //    ddl.Items.Add(new ListItem("36-50(15%)", "36"));
    //    ddl.Items.Add(new ListItem(">50(20%)", "50"));
    //}

    #endregion

    #region Not Use
    //private void GetCarModelSumInsuredAmountAndVehicleType(string CarMake, string CarModel, string Body, string CC, string Door, string Year, out string SumInsured)
    //{
    //    MyDatabase _db = new MyDatabase();
    //    DataTable _dt = new DataTable("tblModelBody");
    //    SortedList _spList = new SortedList();
    //    _spList.Add("@CarMake", CarMake);
    //    _spList.Add("@CarModel", CarModel);
    //    _spList.Add("@Body", Body);
    //    _spList.Add("@CC", CC);
    //    _spList.Add("@Door", Door);
    //    _spList.Add("@Year", Year);
    //    _dt = _db.GetDataTableBySP("sprocGetCarModelSumInsuredAndVehicleTypeTHListByYear", _spList);
    //    if (_dt != null && _dt.Rows.Count > 0)
    //    {
    //        SumInsured = _dt.Rows[0][0].ToString();
    //    }
    //    else
    //    {
    //        SumInsured = "0";
    //    }
    //    _dt = null;
    //    _db = null;
    //}

    //private string GetSumInsured()
    //{
    //    string sumInsured = "";
    //    if (ddlNCarYear.SelectedIndex >= 0 && ddlNCarMake.SelectedIndex >= 0 & ddlNModelBodyCCDoor.SelectedIndex >= 0)
    //    {
    //        string[] _tempDesc = ddlNModelBodyCCDoor.Text.Split(' ');
    //        string _model = "";
    //        string _body = "";
    //        string _cc = "";
    //        string _door = "";
    //        if (_tempDesc.Length == 5)
    //        {
    //            _model = _tempDesc[0];
    //            _body = _tempDesc[1];
    //            _cc = _tempDesc[2].Substring(0, _tempDesc[2].Length - 2);
    //            _door = _tempDesc[3];
    //        }
    //        else if (_tempDesc.Length == 6)
    //        {
    //            _model = _tempDesc[0] + " " + _tempDesc[1];
    //            _body = _tempDesc[2];
    //            _cc = _tempDesc[3].Substring(0, _tempDesc[3].Length - 2);
    //            _door = _tempDesc[4];
    //        }
    //        else if (_tempDesc.Length == 7)
    //        {
    //            _model = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
    //            _body = _tempDesc[3];
    //            _cc = _tempDesc[4].Substring(0, _tempDesc[4].Length - 2);
    //            _door = _tempDesc[5];
    //        }
    //        GetCarModelSumInsuredAmountAndVehicleType(ddlNCarMake.Text, _model, _body, _cc, _door, ddlNCarYear.Text, out sumInsured);
    //    }
    //    return sumInsured;
    //}
    #endregion

    #endregion

}
